has_many_associations_test.rb 88.8 KB
Newer Older
1 2
# frozen_string_literal: true

3
require "cases/helper"
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
require "models/developer"
require "models/computer"
require "models/project"
require "models/company"
require "models/contract"
require "models/topic"
require "models/reply"
require "models/category"
require "models/image"
require "models/post"
require "models/author"
require "models/essay"
require "models/comment"
require "models/person"
require "models/reader"
require "models/tagging"
require "models/tag"
require "models/invoice"
require "models/line_item"
require "models/car"
require "models/bulb"
require "models/engine"
require "models/categorization"
require "models/minivan"
require "models/speedometer"
require "models/reference"
require "models/college"
require "models/student"
require "models/pirate"
require "models/ship"
require "models/ship_part"
require "models/treasure"
require "models/parrot"
require "models/tyre"
require "models/subscriber"
require "models/subscription"
require "models/zine"
require "models/interest"
42

43
class HasManyAssociationsTestForReorderWithJoinDependency < ActiveRecord::TestCase
44
  fixtures :authors, :author_addresses, :posts, :comments
45 46 47 48 49

  def test_should_generate_valid_sql
    author = authors(:david)
    # this can fail on adapters which require ORDER BY expressions to be included in the SELECT expression
    # if the reorder clauses are not correctly handled
50
    assert author.posts_with_comments_sorted_by_comment_id.where("comments.id > 0").reorder("posts.comments_count DESC", "posts.tags_count DESC").last
51 52
  end
end
53

54
class HasManyAssociationsTestPrimaryKeys < ActiveRecord::TestCase
55
  fixtures :authors, :author_addresses, :essays, :subscribers, :subscriptions, :people
56 57

  def test_custom_primary_key_on_new_record_should_fetch_with_query
58
    subscriber = Subscriber.new(nick: "webster132")
59
    assert_not_predicate subscriber.subscriptions, :loaded?
60 61 62 63 64

    assert_queries 1 do
      assert_equal 2, subscriber.subscriptions.size
    end

65
    assert_equal Subscription.where(subscriber_id: "webster132"), subscriber.subscriptions
66 67 68
  end

  def test_association_primary_key_on_new_record_should_fetch_with_query
69
    author = Author.new(name: "David")
70
    assert_not_predicate author.essays, :loaded?
71 72 73 74 75

    assert_queries 1 do
      assert_equal 1, author.essays.size
    end

76
    assert_equal Essay.where(writer_id: "David"), author.essays
77 78 79 80
  end

  def test_has_many_custom_primary_key
    david = authors(:david)
81 82 83 84 85 86 87 88 89 90 91 92
    assert_equal Essay.where(writer_id: "David"), david.essays
  end

  def test_ids_on_unloaded_association_with_custom_primary_key
    david = people(:david)
    assert_equal Essay.where(writer_id: "David").pluck(:id), david.essay_ids
  end

  def test_ids_on_loaded_association_with_custom_primary_key
    david = people(:david)
    david.essays.load
    assert_equal Essay.where(writer_id: "David").pluck(:id), david.essay_ids
93 94 95 96 97 98
  end

  def test_has_many_assignment_with_custom_primary_key
    david = people(:david)

    assert_equal ["A Modest Proposal"], david.essays.map(&:name)
99
    david.essays = [Essay.create!(name: "Remote Work")]
100 101 102 103 104
    assert_equal ["Remote Work"], david.essays.map(&:name)
  end

  def test_blank_custom_primary_key_on_new_record_should_not_run_queries
    author = Author.new
105
    assert_not_predicate author.essays, :loaded?
106 107 108 109 110 111

    assert_queries 0 do
      assert_equal 0, author.essays.size
    end
  end
end
112 113 114

class HasManyAssociationsTest < ActiveRecord::TestCase
  fixtures :accounts, :categories, :companies, :developers, :projects,
115
           :developers_projects, :topics, :authors, :author_addresses, :comments,
R
Ryuta Kamizono 已提交
116
           :posts, :readers, :taggings, :cars, :tags,
117
           :categorizations, :zines, :interests
118 119 120 121 122

  def setup
    Client.destroyed_client_ids.clear
  end

123 124 125 126 127 128
  def test_sti_subselect_count
    tag = Tag.first
    len = Post.tagged_with(tag.id).limit(10).size
    assert_operator len, :>, 0
  end

129 130
  def test_anonymous_has_many
    developer = Class.new(ActiveRecord::Base) {
131
      self.table_name = "developers"
132 133 134
      dev = self

      developer_project = Class.new(ActiveRecord::Base) {
135
        self.table_name = "developers_projects"
136
        belongs_to :developer, anonymous_class: dev
137
      }
138
      has_many :developer_projects, anonymous_class: developer_project, foreign_key: "developer_id"
139 140 141 142 143 144 145 146
    }
    dev = developer.first
    named = Developer.find(dev.id)
    assert_operator dev.developer_projects.count, :>, 0
    assert_equal named.projects.map(&:id).sort,
                 dev.developer_projects.map(&:project_id).sort
  end

147 148 149
  def test_default_scope_on_relations_is_not_cached
    counter = 0
    posts = Class.new(ActiveRecord::Base) {
150 151
      self.table_name = "posts"
      self.inheritance_column = "not_there"
152 153 154
      post = self

      comments = Class.new(ActiveRecord::Base) {
155 156
        self.table_name = "comments"
        self.inheritance_column = "not_there"
157
        belongs_to :post, anonymous_class: post
158 159
        default_scope -> {
          counter += 1
160
          where("id = :inc", inc: counter)
161 162
        }
      }
163
      has_many :comments, anonymous_class: comments, foreign_key: "post_id"
164 165 166 167 168 169 170 171 172
    }
    assert_equal 0, counter
    post = posts.first
    assert_equal 0, counter
    sql = capture_sql { post.comments.to_a }
    post.comments.reset
    assert_not_equal sql, capture_sql { post.comments.to_a }
  end

173
  def test_has_many_build_with_options
174 175
    college = College.create(name: "UFMT")
    Student.create(active: true, college_id: college.id, name: "Sarah")
176 177 178 179

    assert_equal college.students, Student.where(active: true, college_id: college.id)
  end

180
  def test_add_record_to_collection_should_change_its_updated_at
181 182
    ship = Ship.create(name: "dauntless")
    part = ShipPart.create(name: "cockpit")
183 184
    updated_at = part.updated_at

185 186 187
    travel(1.second) do
      ship.parts << part
    end
188 189 190 191 192 193 194 195

    assert_equal part.ship, ship
    assert_not_equal part.updated_at, updated_at
  end

  def test_clear_collection_should_not_change_updated_at
    # GH#17161: .clear calls delete_all (and returns the association),
    # which is intended to not touch associated objects's updated_at field
196 197
    ship = Ship.create(name: "dauntless")
    part = ShipPart.create(name: "cockpit", ship_id: ship.id)
198 199 200 201

    ship.parts.clear
    part.reload

202
    assert_nil part.ship
203
    assert_not_predicate part, :updated_at_changed?
204 205
  end

206
  def test_create_from_association_should_respect_default_scope
207
    car = Car.create(name: "honda")
208
    assert_equal "honda", car.name
209 210

    bulb = Bulb.create
211
    assert_equal "defaulty", bulb.name
212 213

    bulb = car.bulbs.build
214
    assert_equal "defaulty", bulb.name
215 216

    bulb = car.bulbs.create
217
    assert_equal "defaulty", bulb.name
218 219 220
  end

  def test_build_and_create_from_association_should_respect_passed_attributes_over_default_scope
221
    car = Car.create(name: "honda")
222

223 224
    bulb = car.bulbs.build(name: "exotic")
    assert_equal "exotic", bulb.name
225

226 227
    bulb = car.bulbs.create(name: "exotic")
    assert_equal "exotic", bulb.name
228 229 230 231 232 233

    bulb = car.awesome_bulbs.build(frickinawesome: false)
    assert_equal false, bulb.frickinawesome

    bulb = car.awesome_bulbs.create(frickinawesome: false)
    assert_equal false, bulb.frickinawesome
234 235
  end

236 237 238 239
  def test_build_from_association_should_respect_scope
    author = Author.new

    post = author.thinking_posts.build
240
    assert_equal "So I was thinking", post.title
241 242
  end

243
  def test_create_from_association_with_nil_values_should_work
244
    car = Car.create(name: "honda")
245 246

    bulb = car.bulbs.new(nil)
247
    assert_equal "defaulty", bulb.name
248 249

    bulb = car.bulbs.build(nil)
250
    assert_equal "defaulty", bulb.name
251 252

    bulb = car.bulbs.create(nil)
253
    assert_equal "defaulty", bulb.name
254 255
  end

256 257 258 259 260 261 262
  def test_build_from_association_sets_inverse_instance
    car = Car.new(name: "honda")

    bulb = car.bulbs.build
    assert_equal car, bulb.car
  end

263
  def test_do_not_call_callbacks_for_delete_all
264
    car = Car.create(name: "honda")
265
    car.funky_bulbs.create!
266
    assert_equal 1, car.funky_bulbs.count
267
    assert_nothing_raised { car.reload.funky_bulbs.delete_all }
268
    assert_equal 0, car.funky_bulbs.count, "bulbs should have been deleted using :delete_all strategy"
269 270
  end

271 272
  def test_delete_all_on_association_is_the_same_as_not_loaded
    author = authors :david
273
    author.thinking_posts.create!(body: "test")
274 275 276
    author.reload
    expected_sql = capture_sql { author.thinking_posts.delete_all }

277
    author.thinking_posts.create!(body: "test")
278 279 280 281 282 283
    author.reload
    author.thinking_posts.inspect
    loaded_sql = capture_sql { author.thinking_posts.delete_all }
    assert_equal(expected_sql, loaded_sql)
  end

284 285
  def test_delete_all_on_association_with_nil_dependency_is_the_same_as_not_loaded
    author = authors :david
286
    author.posts.create!(title: "test", body: "body")
287 288 289
    author.reload
    expected_sql = capture_sql { author.posts.delete_all }

290
    author.posts.create!(title: "test", body: "body")
291 292 293 294 295 296
    author.reload
    author.posts.to_a
    loaded_sql = capture_sql { author.posts.delete_all }
    assert_equal(expected_sql, loaded_sql)
  end

297 298 299
  def test_building_the_associated_object_with_implicit_sti_base_class
    firm = DependentFirm.new
    company = firm.companies.build
300
    assert_kind_of Company, company, "Expected #{company.class} to be a Company"
301 302 303 304
  end

  def test_building_the_associated_object_with_explicit_sti_base_class
    firm = DependentFirm.new
305
    company = firm.companies.build(type: "Company")
306
    assert_kind_of Company, company, "Expected #{company.class} to be a Company"
307 308 309 310
  end

  def test_building_the_associated_object_with_sti_subclass
    firm = DependentFirm.new
311
    company = firm.companies.build(type: "Client")
312
    assert_kind_of Client, company, "Expected #{company.class} to be a Client"
313 314 315 316
  end

  def test_building_the_associated_object_with_an_invalid_type
    firm = DependentFirm.new
317
    assert_raise(ActiveRecord::SubclassNotFound) { firm.companies.build(type: "Invalid") }
318 319 320 321
  end

  def test_building_the_associated_object_with_an_unrelated_type
    firm = DependentFirm.new
322
    assert_raise(ActiveRecord::SubclassNotFound) { firm.companies.build(type: "Account") }
323 324
  end

325 326
  test "building the association with an array" do
    speedometer = Speedometer.new(speedometer_id: "a")
327
    data = [{ name: "first" }, { name: "second" }]
328 329 330 331 332 333 334
    speedometer.minivans.build(data)

    assert_equal 2, speedometer.minivans.size
    assert speedometer.save
    assert_equal ["first", "second"], speedometer.reload.minivans.map(&:name)
  end

335
  def test_association_keys_bypass_attribute_protection
336
    car = Car.create(name: "honda")
337 338 339 340

    bulb = car.bulbs.new
    assert_equal car.id, bulb.car_id

341
    bulb = car.bulbs.new car_id: car.id + 1
342 343
    assert_equal car.id, bulb.car_id

344 345 346
    bulb = car.bulbs.build
    assert_equal car.id, bulb.car_id

347
    bulb = car.bulbs.build car_id: car.id + 1
348 349
    assert_equal car.id, bulb.car_id

350 351
    bulb = car.bulbs.create
    assert_equal car.id, bulb.car_id
352

353
    bulb = car.bulbs.create car_id: car.id + 1
354
    assert_equal car.id, bulb.car_id
355 356
  end

357 358 359 360 361 362
  def test_association_protect_foreign_key
    invoice = Invoice.create

    line_item = invoice.line_items.new
    assert_equal invoice.id, line_item.invoice_id

363
    line_item = invoice.line_items.new invoice_id: invoice.id + 1
364 365 366 367 368
    assert_equal invoice.id, line_item.invoice_id

    line_item = invoice.line_items.build
    assert_equal invoice.id, line_item.invoice_id

369
    line_item = invoice.line_items.build invoice_id: invoice.id + 1
370 371 372 373 374
    assert_equal invoice.id, line_item.invoice_id

    line_item = invoice.line_items.create
    assert_equal invoice.id, line_item.invoice_id

375
    line_item = invoice.line_items.create invoice_id: invoice.id + 1
376 377 378
    assert_equal invoice.id, line_item.invoice_id
  end

R
Rich 已提交
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
  class SpecialAuthor < ActiveRecord::Base
    self.table_name = "authors"
    has_many :books, class_name: "SpecialBook", foreign_key: :author_id
  end

  class SpecialBook < ActiveRecord::Base
    self.table_name = "books"

    belongs_to :author
    enum read_status: { unread: 0, reading: 2, read: 3, forgotten: nil }
  end

  def test_association_enum_works_properly
    author = SpecialAuthor.create!(name: "Test")
    book = SpecialBook.create!(read_status: "reading")
    author.books << book

    assert_equal "reading", book.read_status
    assert_not_equal 0, SpecialAuthor.joins(:books).where(books: { read_status: "reading" }).count
  end

400 401 402 403
  # When creating objects on the association, we must not do it within a scope (even though it
  # would be convenient), because this would cause that scope to be applied to any callbacks etc.
  def test_build_and_create_should_not_happen_within_scope
    car = cars(:honda)
404
    scope = car.foo_bulbs.where_values_hash
405

406
    bulb = car.foo_bulbs.build
407
    assert_not_equal scope, bulb.scope_after_initialize.where_values_hash
408

409
    bulb = car.foo_bulbs.create
410
    assert_not_equal scope, bulb.scope_after_initialize.where_values_hash
411

412
    bulb = car.foo_bulbs.create!
413
    assert_not_equal scope, bulb.scope_after_initialize.where_values_hash
414 415
  end

416
  def test_no_sql_should_be_fired_if_association_already_loaded
417
    Car.create(name: "honda")
418
    bulbs = Car.first.bulbs
B
Brian Cardarella 已提交
419
    bulbs.to_a # to load all instances of bulbs
420

421 422 423
    assert_no_queries do
      bulbs.first()
    end
424

425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
    assert_no_queries do
      bulbs.second()
    end

    assert_no_queries do
      bulbs.third()
    end

    assert_no_queries do
      bulbs.fourth()
    end

    assert_no_queries do
      bulbs.fifth()
    end

    assert_no_queries do
      bulbs.forty_two()
    end

445
    assert_no_queries do
446
      bulbs.third_to_last()
447 448 449
    end

    assert_no_queries do
450
      bulbs.second_to_last()
451 452
    end

453 454 455
    assert_no_queries do
      bulbs.last()
    end
456 457
  end

458 459 460 461 462 463 464 465 466
  def test_finder_method_with_dirty_target
    company = companies(:first_firm)
    new_clients = []
    assert_no_queries(ignore_none: false) do
      new_clients << company.clients_of_firm.build(name: "Another Client")
      new_clients << company.clients_of_firm.build(name: "Another Client II")
      new_clients << company.clients_of_firm.build(name: "Another Client III")
    end

467
    assert_not_predicate company.clients_of_firm, :loaded?
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
    assert_queries(1) do
      assert_same new_clients[0], company.clients_of_firm.third
      assert_same new_clients[1], company.clients_of_firm.fourth
      assert_same new_clients[2], company.clients_of_firm.fifth
      assert_same new_clients[0], company.clients_of_firm.third_to_last
      assert_same new_clients[1], company.clients_of_firm.second_to_last
      assert_same new_clients[2], company.clients_of_firm.last
    end
  end

  def test_finder_bang_method_with_dirty_target
    company = companies(:first_firm)
    new_clients = []
    assert_no_queries(ignore_none: false) do
      new_clients << company.clients_of_firm.build(name: "Another Client")
      new_clients << company.clients_of_firm.build(name: "Another Client II")
      new_clients << company.clients_of_firm.build(name: "Another Client III")
    end

487
    assert_not_predicate company.clients_of_firm, :loaded?
488 489 490 491 492 493 494 495 496 497
    assert_queries(1) do
      assert_same new_clients[0], company.clients_of_firm.third!
      assert_same new_clients[1], company.clients_of_firm.fourth!
      assert_same new_clients[2], company.clients_of_firm.fifth!
      assert_same new_clients[0], company.clients_of_firm.third_to_last!
      assert_same new_clients[1], company.clients_of_firm.second_to_last!
      assert_same new_clients[2], company.clients_of_firm.last!
    end
  end

498
  def test_create_resets_cached_counters
499 500
    Reader.delete_all

501
    person = Person.create!(first_name: "tenderlove")
502

503
    post   = Post.first
504 505

    assert_equal [], person.readers
506
    assert_nil person.readers.find_by_post_id(post.id)
507

508
    person.readers.create(post_id: post.id)
509 510 511 512 513 514 515

    assert_equal 1, person.readers.count
    assert_equal 1, person.readers.length
    assert_equal post, person.readers.first.post
    assert_equal person, person.readers.first.person
  end

516 517
  def test_update_all_respects_association_scope
    person = Person.new
518
    person.first_name = "Naruto"
519 520 521 522 523 524 525
    person.references << Reference.new
    person.save!
    assert_equal 1, person.references.update_all(favourite: true)
  end

  def test_exists_respects_association_scope
    person = Person.new
526
    person.first_name = "Sasuke"
527 528 529 530 531
    person.references << Reference.new
    person.save!
    assert_predicate person.references, :exists?
  end

532
  def test_counting_with_counter_sql
533
    assert_equal 3, Firm.first.clients.count
534 535 536
  end

  def test_counting
537
    assert_equal 3, Firm.first.plain_clients.count
538 539 540
  end

  def test_counting_with_single_hash
541
    assert_equal 1, Firm.first.plain_clients.where(name: "Microsoft").count
542 543 544
  end

  def test_counting_with_column_name_and_hash
545
    assert_equal 3, Firm.first.plain_clients.count(:name)
546 547
  end

548 549 550 551 552 553
  def test_counting_with_association_limit
    firm = companies(:first_firm)
    assert_equal firm.limited_clients.length, firm.limited_clients.size
    assert_equal firm.limited_clients.length, firm.limited_clients.count
  end

554
  def test_finding
555
    assert_equal 3, Firm.first.clients.length
556 557
  end

558
  def test_finding_array_compatibility
559
    assert_equal 3, Firm.order(:id).find { |f| f.id > 0 }.clients.length
560 561
  end

562 563
  def test_find_many_with_merged_options
    assert_equal 1, companies(:first_firm).limited_clients.size
564
    assert_equal 1, companies(:first_firm).limited_clients.to_a.size
565
    assert_equal 3, companies(:first_firm).limited_clients.limit(nil).to_a.size
566 567
  end

568
  def test_find_should_append_to_association_order
569
    ordered_clients = companies(:first_firm).clients_sorted_desc.order("companies.id")
570
    assert_equal ["id DESC", "companies.id"], ordered_clients.order_values
571 572
  end

573
  def test_dynamic_find_should_respect_association_order
574
    assert_equal companies(:another_first_firm_client), companies(:first_firm).clients_sorted_desc.where("type = 'Client'").first
575
    assert_equal companies(:another_first_firm_client), companies(:first_firm).clients_sorted_desc.find_by_type("Client")
576 577
  end

578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
  def test_taking
    posts(:other_by_bob).destroy
    assert_equal posts(:misc_by_bob), authors(:bob).posts.take
    assert_equal posts(:misc_by_bob), authors(:bob).posts.take!
    authors(:bob).posts.to_a
    assert_equal posts(:misc_by_bob), authors(:bob).posts.take
    assert_equal posts(:misc_by_bob), authors(:bob).posts.take!
  end

  def test_taking_not_found
    authors(:bob).posts.delete_all
    assert_raise(ActiveRecord::RecordNotFound) { authors(:bob).posts.take! }
    authors(:bob).posts.to_a
    assert_raise(ActiveRecord::RecordNotFound) { authors(:bob).posts.take! }
  end

594
  def test_taking_with_a_number
595 596 597 598 599 600 601 602
    klass = Class.new(Author) do
      has_many :posts, -> { order(:id) }

      def self.name
        "Author"
      end
    end

603
    # taking from unloaded Relation
604
    bob = klass.find(authors(:bob).id)
605
    new_post = bob.posts.build
606
    assert_not_predicate bob.posts, :loaded?
607 608
    assert_equal [posts(:misc_by_bob)], bob.posts.take(1)
    assert_equal [posts(:misc_by_bob), posts(:other_by_bob)], bob.posts.take(2)
609
    assert_equal [posts(:misc_by_bob), posts(:other_by_bob), new_post], bob.posts.take(3)
610 611

    # taking from loaded Relation
612
    bob.posts.load
613
    assert_predicate bob.posts, :loaded?
614 615 616
    assert_equal [posts(:misc_by_bob)], bob.posts.take(1)
    assert_equal [posts(:misc_by_bob), posts(:other_by_bob)], bob.posts.take(2)
    assert_equal [posts(:misc_by_bob), posts(:other_by_bob), new_post], bob.posts.take(3)
617 618
  end

619 620 621 622 623 624 625 626 627 628
  def test_taking_with_inverse_of
    interests(:woodsmanship).destroy
    interests(:survival).destroy

    zine = zines(:going_out)
    interest = zine.interests.take
    assert_equal interests(:hunting), interest
    assert_same zine, interest.zine
  end

629 630 631 632 633 634
  def test_cant_save_has_many_readonly_association
    authors(:david).readonly_comments.each { |c| assert_raise(ActiveRecord::ReadOnlyRecord) { c.save! } }
    authors(:david).readonly_comments.each { |c| assert c.readonly? }
  end

  def test_finding_default_orders
635
    assert_equal "Summit", Firm.first.clients.first.name
636 637 638
  end

  def test_finding_with_different_class_name_and_order
639
    assert_equal "Apex", Firm.first.clients_sorted_desc.first.name
640 641 642
  end

  def test_finding_with_foreign_key
643
    assert_equal "Microsoft", Firm.first.clients_of_firm.first.name
644 645 646
  end

  def test_finding_with_condition
647
    assert_equal "Microsoft", Firm.first.clients_like_ms.first.name
648 649 650
  end

  def test_finding_with_condition_hash
651
    assert_equal "Microsoft", Firm.first.clients_like_ms_with_hash_conditions.first.name
652 653
  end

654
  def test_finding_using_primary_key
655
    assert_equal "Summit", Firm.first.clients_using_primary_key.first.name
656 657
  end

658
  def test_update_all_on_association_accessed_before_save
659
    firm = Firm.new(name: "Firm")
660 661
    firm.clients << Client.first
    firm.save!
662
    assert_equal firm.clients.count, firm.clients.update_all(description: "Great!")
663 664 665
  end

  def test_update_all_on_association_accessed_before_save_with_explicit_foreign_key
666
    firm = Firm.new(name: "Firm", id: 100)
667 668
    firm.clients << Client.first
    firm.save!
669
    assert_equal firm.clients.count, firm.clients.update_all(description: "Great!")
670 671
  end

672 673
  def test_belongs_to_sanity
    c = Client.new
674
    assert_nil c.firm, "belongs_to failed sanity check on new object"
675 676 677
  end

  def test_find_ids
678
    firm = Firm.first
679

680
    assert_raise(ActiveRecord::RecordNotFound) { firm.clients.find }
681 682 683 684 685 686 687 688 689 690 691 692 693

    client = firm.clients.find(2)
    assert_kind_of Client, client

    client_ary = firm.clients.find([2])
    assert_kind_of Array, client_ary
    assert_equal client, client_ary.first

    client_ary = firm.clients.find(2, 3)
    assert_kind_of Array, client_ary
    assert_equal 2, client_ary.size
    assert_equal client, client_ary.first

694
    assert_raise(ActiveRecord::RecordNotFound) { firm.clients.find(2, 99) }
695 696
  end

697
  def test_find_one_message_on_primary_key
698
    firm = Firm.first
699 700 701 702 703 704 705 706 707 708

    e = assert_raises(ActiveRecord::RecordNotFound) do
      firm.clients.find(0)
    end
    assert_equal 0, e.id
    assert_equal "id", e.primary_key
    assert_equal "Client", e.model
    assert_match (/\ACouldn't find Client with 'id'=0/), e.message
  end

A
Arthur Neves 已提交
709 710 711
  def test_find_ids_and_inverse_of
    force_signal37_to_load_all_clients_of_firm

712 713
    assert_predicate companies(:first_firm).clients_of_firm, :loaded?

A
Arthur Neves 已提交
714 715 716 717 718 719 720 721 722
    firm = companies(:first_firm)
    client = firm.clients_of_firm.find(3)
    assert_kind_of Client, client

    client_ary = firm.clients_of_firm.find([3])
    assert_kind_of Array, client_ary
    assert_equal client, client_ary.first
  end

723
  def test_find_all
724
    firm = Firm.first
725
    assert_equal 3, firm.clients.where("#{QUOTED_TYPE} = 'Client'").to_a.length
726
    assert_equal 1, firm.clients.where("name = 'Summit'").to_a.length
727 728
  end

729 730 731
  def test_find_each
    firm = companies(:first_firm)

D
Daniel Colson 已提交
732
    assert_not_predicate firm.clients, :loaded?
733

734
    assert_queries(4) do
735
      firm.clients.find_each(batch_size: 1) { |c| assert_equal firm.id, c.firm_id }
736 737
    end

D
Daniel Colson 已提交
738
    assert_not_predicate firm.clients, :loaded?
739 740 741 742 743 744
  end

  def test_find_each_with_conditions
    firm = companies(:first_firm)

    assert_queries(2) do
745
      firm.clients.where(name: "Microsoft").find_each(batch_size: 1) do |c|
746 747 748 749 750
        assert_equal firm.id, c.firm_id
        assert_equal "Microsoft", c.name
      end
    end

D
Daniel Colson 已提交
751
    assert_not_predicate firm.clients, :loaded?
752 753 754 755 756
  end

  def test_find_in_batches
    firm = companies(:first_firm)

D
Daniel Colson 已提交
757
    assert_not_predicate firm.clients, :loaded?
758 759

    assert_queries(2) do
760
      firm.clients.find_in_batches(batch_size: 2) do |clients|
761
        clients.each { |c| assert_equal firm.id, c.firm_id }
762 763 764
      end
    end

D
Daniel Colson 已提交
765
    assert_not_predicate firm.clients, :loaded?
766 767
  end

768
  def test_find_all_sanitized
769
    firm = Firm.first
770 771
    summit = firm.clients.where("name = 'Summit'").to_a
    assert_equal summit, firm.clients.where("name = ?", "Summit").to_a
772
    assert_equal summit, firm.clients.where("name = :name", name: "Summit").to_a
773 774 775
  end

  def test_find_first
776
    firm = Firm.first
777
    client2 = Client.find(2)
778 779
    assert_equal firm.clients.first, firm.clients.order("id").first
    assert_equal client2, firm.clients.where("#{QUOTED_TYPE} = 'Client'").order("id").first
780 781 782
  end

  def test_find_first_sanitized
783
    firm = Firm.first
784
    client2 = Client.find(2)
785 786
    assert_equal client2, firm.clients.where("#{QUOTED_TYPE} = ?", "Client").first
    assert_equal client2, firm.clients.where("#{QUOTED_TYPE} = :type", type: "Client").first
787 788
  end

789
  def test_find_first_after_reset_scope
790
    firm = Firm.first
791 792
    collection = firm.clients

793 794
    original_object = collection.first
    assert_same original_object, collection.first, "Expected second call to #first to cache the same object"
795 796

    # It should return a different object, since the association has been reloaded
797
    assert_not_same original_object, firm.clients.first, "Expected #first to return a new object"
798
  end
799

800
  def test_find_first_after_reset
801
    firm = Firm.first
802
    collection = firm.clients
803

804 805
    original_object = collection.first
    assert_same original_object, collection.first, "Expected second call to #first to cache the same object"
806
    collection.reset
807 808

    # It should return a different object, since the association has been reloaded
809
    assert_not_same original_object, collection.first, "Expected #first after #reset to return a new object"
810 811 812
  end

  def test_find_first_after_reload
813
    firm = Firm.first
814
    collection = firm.clients
815

816 817 818
    original_object = collection.first
    assert_same original_object, collection.first, "Expected second call to #first to cache the same object"
    collection.reload
819 820

    # It should return a different object, since the association has been reloaded
821
    assert_not_same original_object, collection.first, "Expected #first after #reload to return a new object"
822 823
  end

824 825
  def test_find_all_with_include_and_conditions
    assert_nothing_raised do
826
      Developer.all.merge!(joins: :audit_logs, where: { "audit_logs.message" => nil, :name => "Smith" }).to_a
827 828 829
    end
  end

830 831
  def test_find_in_collection
    assert_equal Client.find(2).name, companies(:first_firm).clients.find(2).name
832
    assert_raise(ActiveRecord::RecordNotFound) { companies(:first_firm).clients.find(6) }
833 834 835
  end

  def test_find_grouped
836 837
    all_clients_of_firm1 = Client.all.merge!(where: "firm_id = 1").to_a
    grouped_clients_of_firm1 = Client.all.merge!(where: "firm_id = 1", group: "firm_id", select: "firm_id, count(id) as clients_count").to_a
838
    assert_equal 3, all_clients_of_firm1.size
839 840 841
    assert_equal 1, grouped_clients_of_firm1.size
  end

842
  def test_find_scoped_grouped
843
    assert_equal 1, companies(:first_firm).clients_grouped_by_firm_id.size
844
    assert_equal 1, companies(:first_firm).clients_grouped_by_firm_id.length
845 846
    assert_equal 3, companies(:first_firm).clients_grouped_by_name.size
    assert_equal 3, companies(:first_firm).clients_grouped_by_name.length
847 848
  end

849
  def test_find_scoped_grouped_having
850
    assert_equal 2, authors(:david).popular_grouped_posts.length
851 852 853
    assert_equal 0, authors(:mary).popular_grouped_posts.length
  end

854
  def test_default_select
855
    assert_equal Comment.column_names.sort, posts(:welcome).comments.first.attributes.keys.sort
856 857 858
  end

  def test_select_query_method
859
    assert_equal ["id", "body"], posts(:welcome).comments.select(:id, :body).first.attributes.keys
860 861 862 863
  end

  def test_select_with_block
    assert_equal [1], posts(:welcome).comments.select { |c| c.id == 1 }.map(&:id)
864 865
  end

866 867 868 869 870 871
  def test_select_with_block_and_dirty_target
    assert_equal 2, posts(:welcome).comments.select { true }.size
    posts(:welcome).comments.build
    assert_equal 3, posts(:welcome).comments.select { true }.size
  end

872
  def test_select_without_foreign_key
873
    assert_equal companies(:first_firm).accounts.first.credit_limit, companies(:first_firm).accounts.select(:credit_limit).first.credit_limit
874
  end
875

876 877
  def test_adding
    force_signal37_to_load_all_clients_of_firm
878 879 880

    assert_predicate companies(:first_firm).clients_of_firm, :loaded?

881 882
    natural = Client.new("name" => "Natural Company")
    companies(:first_firm).clients_of_firm << natural
883
    assert_equal 3, companies(:first_firm).clients_of_firm.size # checking via the collection
884
    assert_equal 3, companies(:first_firm).clients_of_firm.reload.size # checking using the db
885 886 887 888 889 890
    assert_equal natural, companies(:first_firm).clients_of_firm.last
  end

  def test_adding_using_create
    first_firm = companies(:first_firm)
    assert_equal 3, first_firm.plain_clients.size
891
    first_firm.plain_clients.create(name: "Natural Company")
892 893
    assert_equal 4, first_firm.plain_clients.length
    assert_equal 4, first_firm.plain_clients.size
894 895 896
  end

  def test_create_with_bang_on_has_many_when_parent_is_new_raises
897
    error = assert_raise(ActiveRecord::RecordNotSaved) do
898
      firm = Firm.new
899
      firm.plain_clients.create! name: "Whoever"
900
    end
901 902

    assert_equal "You cannot call create unless the parent is saved", error.message
903 904 905
  end

  def test_regular_create_on_has_many_when_parent_is_new_raises
906
    error = assert_raise(ActiveRecord::RecordNotSaved) do
907
      firm = Firm.new
908
      firm.plain_clients.create name: "Whoever"
909
    end
910 911

    assert_equal "You cannot call create unless the parent is saved", error.message
912 913 914
  end

  def test_create_with_bang_on_has_many_raises_when_record_not_saved
915
    assert_raise(ActiveRecord::RecordInvalid) do
916
      firm = Firm.first
917 918 919 920 921
      firm.plain_clients.create!
    end
  end

  def test_create_with_bang_on_habtm_when_parent_is_new_raises
922
    error = assert_raise(ActiveRecord::RecordNotSaved) do
923 924
      Developer.new("name" => "Aredridel").projects.create!
    end
925 926

    assert_equal "You cannot call create unless the parent is saved", error.message
927 928 929
  end

  def test_adding_a_mismatch_class
930 931 932
    assert_raise(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).clients_of_firm << nil }
    assert_raise(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).clients_of_firm << 1 }
    assert_raise(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).clients_of_firm << Topic.find(1) }
933 934 935 936
  end

  def test_adding_a_collection
    force_signal37_to_load_all_clients_of_firm
937 938 939

    assert_predicate companies(:first_firm).clients_of_firm, :loaded?

940
    companies(:first_firm).clients_of_firm.concat([Client.new("name" => "Natural Company"), Client.new("name" => "Apple")])
941
    assert_equal 4, companies(:first_firm).clients_of_firm.size
942
    assert_equal 4, companies(:first_firm).clients_of_firm.reload.size
943 944
  end

945
  def test_transactions_when_adding_to_persisted
946 947
    good = Client.new(name: "Good")
    bad  = Client.new(name: "Bad", raise_on_save: true)
J
Jon Leighton 已提交
948 949 950 951 952 953

    begin
      companies(:first_firm).clients_of_firm.concat(good, bad)
    rescue Client::RaisedOnSave
    end

954
    assert_not_includes companies(:first_firm).clients_of_firm.reload, good
955 956 957
  end

  def test_transactions_when_adding_to_new_record
958
    assert_no_queries(ignore_none: false) do
J
Jon Leighton 已提交
959 960 961
      firm = Firm.new
      firm.clients_of_firm.concat(Client.new("name" => "Natural Company"))
    end
962 963
  end

964 965 966 967 968 969 970
  def test_inverse_on_before_validate
    firm = companies(:first_firm)
    assert_queries(1) do
      firm.clients_of_firm << Client.new("name" => "Natural Company")
    end
  end

971 972
  def test_new_aliased_to_build
    company = companies(:first_firm)
973
    new_client = assert_no_queries(ignore_none: false) { company.clients_of_firm.new("name" => "Another Client") }
974
    assert_not_predicate company.clients_of_firm, :loaded?
975 976

    assert_equal "Another Client", new_client.name
977
    assert_not_predicate new_client, :persisted?
978 979 980
    assert_equal new_client, company.clients_of_firm.last
  end

981 982
  def test_build
    company = companies(:first_firm)
983
    new_client = assert_no_queries(ignore_none: false) { company.clients_of_firm.build("name" => "Another Client") }
984
    assert_not_predicate company.clients_of_firm, :loaded?
985

986
    assert_equal "Another Client", new_client.name
987
    assert_not_predicate new_client, :persisted?
988 989 990
    assert_equal new_client, company.clients_of_firm.last
  end

991 992 993 994
  def test_collection_size_after_building
    company = companies(:first_firm)  # company already has one client
    company.clients_of_firm.build("name" => "Another Client")
    company.clients_of_firm.build("name" => "Yet Another Client")
995
    assert_equal 4, company.clients_of_firm.size
996
    assert_equal 4, company.clients_of_firm.uniq.size
997 998
  end

999 1000
  def test_collection_not_empty_after_building
    company = companies(:first_firm)
1001
    assert_empty company.contracts
1002
    company.contracts.build
1003
    assert_not_empty company.contracts
1004 1005
  end

1006 1007 1008 1009 1010 1011
  def test_collection_size_with_dirty_target
    post = posts(:thinking)
    assert_equal [], post.reader_ids
    assert_equal 0, post.readers.size
    post.readers.reset
    post.readers.build
1012
    assert_equal [nil], post.reader_ids
1013 1014 1015
    assert_equal 1, post.readers.size
  end

1016 1017 1018 1019 1020 1021
  def test_collection_empty_with_dirty_target
    post = posts(:thinking)
    assert_equal [], post.reader_ids
    assert_empty post.readers
    post.readers.reset
    post.readers.build
1022
    assert_equal [nil], post.reader_ids
1023 1024 1025
    assert_not_empty post.readers
  end

1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
  def test_collection_size_twice_for_regressions
    post = posts(:thinking)
    assert_equal 0, post.readers.size
    # This test needs a post that has no readers, we assert it to ensure it holds,
    # but need to reload the post because the very call to #size hides the bug.
    post.reload
    post.readers.build
    size1 = post.readers.size
    size2 = post.readers.size
    assert_equal size1, size2
  end

1038 1039
  def test_build_many
    company = companies(:first_firm)
1040
    new_clients = assert_no_queries(ignore_none: false) { company.clients_of_firm.build([{ "name" => "Another Client" }, { "name" => "Another Client II" }]) }
1041 1042 1043 1044
    assert_equal 2, new_clients.size
  end

  def test_build_followed_by_save_does_not_load_target
1045
    companies(:first_firm).clients_of_firm.build("name" => "Another Client")
1046
    assert companies(:first_firm).save
1047
    assert_not_predicate companies(:first_firm).clients_of_firm, :loaded?
1048 1049 1050 1051 1052 1053 1054 1055 1056
  end

  def test_build_without_loading_association
    first_topic = topics(:first)
    Reply.column_names

    assert_equal 1, first_topic.replies.length

    assert_no_queries do
1057
      first_topic.replies.build(title: "Not saved", content: "Superstars")
1058 1059 1060 1061 1062 1063
      assert_equal 2, first_topic.replies.size
    end

    assert_equal 2, first_topic.replies.to_ary.size
  end

1064 1065
  def test_build_via_block
    company = companies(:first_firm)
1066
    new_client = assert_no_queries(ignore_none: false) { company.clients_of_firm.build { |client| client.name = "Another Client" } }
1067
    assert_not_predicate company.clients_of_firm, :loaded?
1068 1069

    assert_equal "Another Client", new_client.name
1070
    assert_not_predicate new_client, :persisted?
1071 1072 1073 1074 1075
    assert_equal new_client, company.clients_of_firm.last
  end

  def test_build_many_via_block
    company = companies(:first_firm)
1076
    new_clients = assert_no_queries(ignore_none: false) do
1077
      company.clients_of_firm.build([{ "name" => "Another Client" }, { "name" => "Another Client II" }]) do |client|
1078 1079 1080 1081 1082 1083 1084 1085 1086
        client.name = "changed"
      end
    end

    assert_equal 2, new_clients.size
    assert_equal "changed", new_clients.first.name
    assert_equal "changed", new_clients.last.name
  end

1087
  def test_create_without_loading_association
1088
    first_firm = companies(:first_firm)
1089 1090 1091
    Firm.column_names
    Client.column_names

1092
    assert_equal 2, first_firm.clients_of_firm.size
1093 1094 1095
    first_firm.clients_of_firm.reset

    assert_queries(1) do
1096
      first_firm.clients_of_firm.create(name: "Superstars")
1097 1098
    end

1099
    assert_equal 3, first_firm.clients_of_firm.size
1100 1101 1102 1103
  end

  def test_create
    force_signal37_to_load_all_clients_of_firm
1104 1105 1106

    assert_predicate companies(:first_firm).clients_of_firm, :loaded?

1107
    new_client = companies(:first_firm).clients_of_firm.create("name" => "Another Client")
1108
    assert_predicate new_client, :persisted?
1109
    assert_equal new_client, companies(:first_firm).clients_of_firm.last
1110
    assert_equal new_client, companies(:first_firm).clients_of_firm.reload.last
1111 1112 1113
  end

  def test_create_many
1114
    companies(:first_firm).clients_of_firm.create([{ "name" => "Another Client" }, { "name" => "Another Client II" }])
1115
    assert_equal 4, companies(:first_firm).clients_of_firm.reload.size
1116 1117 1118
  end

  def test_create_followed_by_save_does_not_load_target
1119
    companies(:first_firm).clients_of_firm.create("name" => "Another Client")
1120
    assert companies(:first_firm).save
1121
    assert_not_predicate companies(:first_firm).clients_of_firm, :loaded?
1122 1123 1124 1125
  end

  def test_deleting
    force_signal37_to_load_all_clients_of_firm
1126 1127 1128

    assert_predicate companies(:first_firm).clients_of_firm, :loaded?

1129
    companies(:first_firm).clients_of_firm.delete(companies(:first_firm).clients_of_firm.first)
1130
    assert_equal 1, companies(:first_firm).clients_of_firm.size
1131
    assert_equal 1, companies(:first_firm).clients_of_firm.reload.size
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
  end

  def test_deleting_before_save
    new_firm = Firm.new("name" => "A New Firm, Inc.")
    new_client = new_firm.clients_of_firm.build("name" => "Another Client")
    assert_equal 1, new_firm.clients_of_firm.size
    new_firm.clients_of_firm.delete(new_client)
    assert_equal 0, new_firm.clients_of_firm.size
  end

1142 1143 1144
  def test_has_many_without_counter_cache_option
    # Ship has a conventionally named `treasures_count` column, but the counter_cache
    # option is not given on the association.
1145
    ship = Ship.create(name: "Countless", treasures_count: 10)
1146

1147
    assert_not_predicate Ship.reflect_on_association(:treasures), :has_cached_counter?
1148 1149 1150 1151 1152

    # Count should come from sql count() of treasures rather than treasures_count attribute
    assert_equal ship.treasures.size, 0

    assert_no_difference lambda { ship.reload.treasures_count }, "treasures_count should not be changed" do
1153
      ship.treasures.create(name: "Gold")
1154 1155 1156 1157 1158 1159 1160
    end

    assert_no_difference lambda { ship.reload.treasures_count }, "treasures_count should not be changed" do
      ship.treasures.destroy_all
    end
  end

1161
  def test_deleting_updates_counter_cache
J
Jon Leighton 已提交
1162
    topic = Topic.order("id ASC").first
1163 1164 1165 1166 1167 1168 1169
    assert_equal topic.replies.to_a.size, topic.replies_count

    topic.replies.delete(topic.replies.first)
    topic.reload
    assert_equal topic.replies.to_a.size, topic.replies_count
  end

1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
  def test_counter_cache_updates_in_memory_after_concat
    topic = Topic.create title: "Zoom-zoom-zoom"

    topic.replies << Reply.create(title: "re: zoom", content: "speedy quick!")
    assert_equal 1, topic.replies_count
    assert_equal 1, topic.replies.size
    assert_equal 1, topic.reload.replies.size
  end

  def test_counter_cache_updates_in_memory_after_create
    topic = Topic.create title: "Zoom-zoom-zoom"

    topic.replies.create!(title: "re: zoom", content: "speedy quick!")
    assert_equal 1, topic.replies_count
    assert_equal 1, topic.replies.size
    assert_equal 1, topic.reload.replies.size
  end

  def test_counter_cache_updates_in_memory_after_create_with_array
    topic = Topic.create title: "Zoom-zoom-zoom"

    topic.replies.create!([
      { title: "re: zoom", content: "speedy quick!" },
      { title: "re: zoom 2", content: "OMG lol!" },
    ])
    assert_equal 2, topic.replies_count
    assert_equal 2, topic.replies.size
    assert_equal 2, topic.reload.replies.size
  end

1200 1201 1202 1203 1204 1205 1206 1207
  def test_counter_cache_updates_in_memory_after_update_with_inverse_of_disabled
    topic = Topic.create!(title: "Zoom-zoom-zoom")

    assert_equal 0, topic.replies_count

    reply1 = Reply.create!(title: "re: zoom", content: "speedy quick!")
    reply2 = Reply.create!(title: "re: zoom 2", content: "OMG lol!")

1208
    assert_queries(4) do
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
      topic.replies << [reply1, reply2]
    end

    assert_equal 2, topic.replies_count
    assert_equal 2, topic.reload.replies_count
  end

  def test_counter_cache_updates_in_memory_after_update_with_inverse_of_enabled
    category = Category.create!(name: "Counter Cache")

    assert_nil category.categorizations_count

    categorization1 = Categorization.create!
    categorization2 = Categorization.create!

    assert_queries(4) do
      category.categorizations << [categorization1, categorization2]
    end

    assert_equal 2, category.categorizations_count
    assert_equal 2, category.reload.categorizations_count
  end

1232 1233 1234 1235 1236 1237 1238 1239 1240
  def test_pushing_association_updates_counter_cache
    topic = Topic.order("id ASC").first
    reply = Reply.create!

    assert_difference "topic.reload.replies_count", 1 do
      topic.replies << reply
    end
  end

1241
  def test_deleting_updates_counter_cache_without_dependent_option
1242 1243
    post = posts(:welcome)

1244
    assert_difference "post.reload.tags_count", -1 do
1245 1246 1247 1248
      post.taggings.delete(post.taggings.first)
    end
  end

1249 1250
  def test_deleting_updates_counter_cache_with_dependent_delete_all
    post = posts(:welcome)
1251
    post.update_columns(taggings_with_delete_all_count: post.tags_count)
1252 1253 1254 1255 1256 1257

    assert_difference "post.reload.taggings_with_delete_all_count", -1 do
      post.taggings_with_delete_all.delete(post.taggings_with_delete_all.first)
    end
  end

1258 1259
  def test_deleting_updates_counter_cache_with_dependent_destroy
    post = posts(:welcome)
1260
    post.update_columns(taggings_with_destroy_count: post.tags_count)
1261 1262 1263 1264 1265 1266

    assert_difference "post.reload.taggings_with_destroy_count", -1 do
      post.taggings_with_destroy.delete(post.taggings_with_destroy.first)
    end
  end

1267 1268 1269
  def test_calling_empty_with_counter_cache
    post = posts(:welcome)
    assert_queries(0) do
1270
      assert_not_empty post.comments
1271 1272 1273
    end
  end

1274 1275 1276 1277 1278 1279 1280 1281
  def test_custom_named_counter_cache
    topic = topics(:first)

    assert_difference "topic.reload.replies_count", -1 do
      topic.approved_replies.clear
    end
  end

1282
  def test_calling_update_on_id_changes_the_counter_cache
1283 1284 1285 1286 1287
    topic = Topic.order("id ASC").first
    original_count = topic.replies.to_a.size
    assert_equal original_count, topic.replies_count

    first_reply = topic.replies.first
1288
    first_reply.update(parent_id: nil)
1289 1290
    assert_equal original_count - 1, topic.reload.replies_count

1291
    first_reply.update(parent_id: topic.id)
1292 1293 1294
    assert_equal original_count, topic.reload.replies_count
  end

1295
  def test_calling_update_changing_ids_doesnt_change_counter_cache
1296 1297 1298 1299 1300 1301 1302 1303
    topic1 = Topic.find(1)
    topic2 = Topic.find(3)
    original_count1 = topic1.replies.to_a.size
    original_count2 = topic2.replies.to_a.size

    reply1 = topic1.replies.first
    reply2 = topic2.replies.first

1304
    reply1.update(parent_id: topic2.id)
1305 1306 1307
    assert_equal original_count1 - 1, topic1.reload.replies_count
    assert_equal original_count2 + 1, topic2.reload.replies_count

1308
    reply2.update(parent_id: topic1.id)
1309 1310 1311 1312
    assert_equal original_count1, topic1.reload.replies_count
    assert_equal original_count2, topic2.reload.replies_count
  end

1313 1314
  def test_deleting_a_collection
    force_signal37_to_load_all_clients_of_firm
1315 1316 1317

    assert_predicate companies(:first_firm).clients_of_firm, :loaded?

1318
    companies(:first_firm).clients_of_firm.create("name" => "Another Client")
1319 1320
    assert_equal 3, companies(:first_firm).clients_of_firm.size
    companies(:first_firm).clients_of_firm.delete([companies(:first_firm).clients_of_firm[0], companies(:first_firm).clients_of_firm[1], companies(:first_firm).clients_of_firm[2]])
1321
    assert_equal 0, companies(:first_firm).clients_of_firm.size
1322
    assert_equal 0, companies(:first_firm).clients_of_firm.reload.size
1323 1324 1325 1326
  end

  def test_delete_all
    force_signal37_to_load_all_clients_of_firm
1327 1328 1329

    assert_predicate companies(:first_firm).clients_of_firm, :loaded?

1330 1331
    companies(:first_firm).dependent_clients_of_firm.create("name" => "Another Client")
    clients = companies(:first_firm).dependent_clients_of_firm.to_a
1332
    assert_equal 3, clients.count
1333 1334

    assert_difference "Client.count", -(clients.count) do
1335
      companies(:first_firm).dependent_clients_of_firm.delete_all
1336
    end
1337 1338 1339 1340
  end

  def test_delete_all_with_not_yet_loaded_association_collection
    force_signal37_to_load_all_clients_of_firm
1341 1342 1343

    assert_predicate companies(:first_firm).clients_of_firm, :loaded?

1344
    companies(:first_firm).clients_of_firm.create("name" => "Another Client")
1345
    assert_equal 3, companies(:first_firm).clients_of_firm.size
1346 1347 1348
    companies(:first_firm).clients_of_firm.reset
    companies(:first_firm).clients_of_firm.delete_all
    assert_equal 0, companies(:first_firm).clients_of_firm.size
1349
    assert_equal 0, companies(:first_firm).clients_of_firm.reload.size
1350 1351
  end

1352
  def test_transaction_when_deleting_persisted
1353 1354
    good = Client.new(name: "Good")
    bad  = Client.new(name: "Bad", raise_on_destroy: true)
J
Jon Leighton 已提交
1355 1356 1357 1358 1359 1360 1361 1362

    companies(:first_firm).clients_of_firm = [good, bad]

    begin
      companies(:first_firm).clients_of_firm.destroy(good, bad)
    rescue Client::RaisedOnDestroy
    end

1363
    assert_equal [good, bad], companies(:first_firm).clients_of_firm.reload
1364 1365 1366
  end

  def test_transaction_when_deleting_new_record
1367
    assert_no_queries(ignore_none: false) do
J
Jon Leighton 已提交
1368 1369 1370 1371 1372
      firm = Firm.new
      client = Client.new("name" => "New Client")
      firm.clients_of_firm << client
      firm.clients_of_firm.destroy(client)
    end
1373 1374
  end

1375 1376 1377
  def test_clearing_an_association_collection
    firm = companies(:first_firm)
    client_id = firm.clients_of_firm.first.id
1378
    assert_equal 2, firm.clients_of_firm.size
1379

J
Jon Leighton 已提交
1380
    firm.clients_of_firm.clear
1381 1382

    assert_equal 0, firm.clients_of_firm.size
1383
    assert_equal 0, firm.clients_of_firm.reload.size
1384 1385 1386 1387
    assert_equal [], Client.destroyed_client_ids[firm.id]

    # Should not be destroyed since the association is not dependent.
    assert_nothing_raised do
1388
      assert_nil Client.find(client_id).firm
1389 1390 1391
    end
  end

1392 1393 1394
  def test_clearing_updates_counter_cache
    topic = Topic.first

1395
    assert_difference "topic.reload.replies_count", -1 do
1396 1397
      topic.replies.clear
    end
1398 1399
  end

1400 1401 1402 1403
  def test_clearing_updates_counter_cache_when_inverse_counter_cache_is_a_symbol_with_dependent_destroy
    car = Car.first
    car.engines.create!

1404
    assert_difference "car.reload.engines_count", -1 do
1405 1406 1407 1408
      car.engines.clear
    end
  end

1409 1410 1411
  def test_clearing_a_dependent_association_collection
    firm = companies(:first_firm)
    client_id = firm.dependent_clients_of_firm.first.id
1412
    assert_equal 2, firm.dependent_clients_of_firm.size
1413
    assert_equal 1, Client.find_by_id(client_id).client_of
1414

1415
    # :delete_all is called on each client since the dependent options is :destroy
1416 1417 1418
    firm.dependent_clients_of_firm.clear

    assert_equal 0, firm.dependent_clients_of_firm.size
1419
    assert_equal 0, firm.dependent_clients_of_firm.reload.size
1420
    assert_equal [], Client.destroyed_client_ids[firm.id]
1421 1422

    # Should be destroyed since the association is dependent.
1423
    assert_nil Client.find_by_id(client_id)
1424 1425 1426 1427 1428 1429
  end

  def test_delete_all_with_option_delete_all
    firm = companies(:first_firm)
    client_id = firm.dependent_clients_of_firm.first.id
    firm.dependent_clients_of_firm.delete_all(:delete_all)
1430
    assert_nil Client.find_by_id(client_id)
1431 1432
  end

1433 1434 1435 1436 1437 1438 1439
  def test_delete_all_accepts_limited_parameters
    firm = companies(:first_firm)
    assert_raise(ArgumentError) do
      firm.dependent_clients_of_firm.delete_all(:destroy)
    end
  end

1440 1441 1442
  def test_clearing_an_exclusively_dependent_association_collection
    firm = companies(:first_firm)
    client_id = firm.exclusively_dependent_clients_of_firm.first.id
1443
    assert_equal 2, firm.exclusively_dependent_clients_of_firm.size
1444 1445 1446 1447 1448 1449 1450 1451

    assert_equal [], Client.destroyed_client_ids[firm.id]

    # :exclusively_dependent means each client is deleted directly from
    # the database without looping through them calling destroy.
    firm.exclusively_dependent_clients_of_firm.clear

    assert_equal 0, firm.exclusively_dependent_clients_of_firm.size
1452
    assert_equal 0, firm.exclusively_dependent_clients_of_firm.reload.size
1453 1454 1455 1456
    # no destroy-filters should have been called
    assert_equal [], Client.destroyed_client_ids[firm.id]

    # Should be destroyed since the association is exclusively dependent.
1457
    assert_nil Client.find_by_id(client_id)
1458 1459 1460 1461
  end

  def test_dependent_association_respects_optional_conditions_on_delete
    firm = companies(:odegy)
1462 1463
    Client.create(client_of: firm.id, name: "BigShot Inc.")
    Client.create(client_of: firm.id, name: "SmallTime Inc.")
1464
    # only one of two clients is included in the association due to the :conditions key
J
Jon Leighton 已提交
1465
    assert_equal 2, Client.where(client_of: firm.id).size
1466 1467 1468
    assert_equal 1, firm.dependent_conditional_clients_of_firm.size
    firm.destroy
    # only the correctly associated client should have been deleted
J
Jon Leighton 已提交
1469
    assert_equal 1, Client.where(client_of: firm.id).size
1470 1471 1472 1473
  end

  def test_dependent_association_respects_optional_sanitized_conditions_on_delete
    firm = companies(:odegy)
1474 1475
    Client.create(client_of: firm.id, name: "BigShot Inc.")
    Client.create(client_of: firm.id, name: "SmallTime Inc.")
1476
    # only one of two clients is included in the association due to the :conditions key
J
Jon Leighton 已提交
1477
    assert_equal 2, Client.where(client_of: firm.id).size
1478 1479 1480
    assert_equal 1, firm.dependent_sanitized_conditional_clients_of_firm.size
    firm.destroy
    # only the correctly associated client should have been deleted
J
Jon Leighton 已提交
1481
    assert_equal 1, Client.where(client_of: firm.id).size
1482 1483
  end

1484 1485
  def test_dependent_association_respects_optional_hash_conditions_on_delete
    firm = companies(:odegy)
1486 1487
    Client.create(client_of: firm.id, name: "BigShot Inc.")
    Client.create(client_of: firm.id, name: "SmallTime Inc.")
1488
    # only one of two clients is included in the association due to the :conditions key
J
Jon Leighton 已提交
1489
    assert_equal 2, Client.where(client_of: firm.id).size
K
Koichi ITO 已提交
1490
    assert_equal 1, firm.dependent_hash_conditional_clients_of_firm.size
1491 1492
    firm.destroy
    # only the correctly associated client should have been deleted
J
Jon Leighton 已提交
1493
    assert_equal 1, Client.where(client_of: firm.id).size
1494 1495
  end

1496
  def test_delete_all_association_with_primary_key_deletes_correct_records
1497
    firm = Firm.first
1498
    # break the vanilla firm_id foreign key
1499
    assert_equal 3, firm.clients.count
1500
    firm.clients.first.update_columns(firm_id: nil)
1501
    assert_equal 2, firm.clients.reload.count
1502
    assert_equal 2, firm.clients_using_primary_key_with_delete_all.count
1503
    old_record = firm.clients_using_primary_key_with_delete_all.first
1504
    firm = Firm.first
1505
    firm.destroy
1506
    assert_nil Client.find_by_id(old_record.id)
1507
  end
1508

1509 1510
  def test_creation_respects_hash_condition
    ms_client = companies(:first_firm).clients_like_ms_with_hash_conditions.build
1511

D
Daniel Colson 已提交
1512 1513
    assert ms_client.save
    assert_equal "Microsoft", ms_client.name
1514

1515 1516
    another_ms_client = companies(:first_firm).clients_like_ms_with_hash_conditions.create

D
Daniel Colson 已提交
1517 1518
    assert_predicate another_ms_client, :persisted?
    assert_equal "Microsoft", another_ms_client.name
1519 1520 1521 1522 1523 1524 1525 1526
  end

  def test_clearing_without_initial_access
    firm = companies(:first_firm)

    firm.clients_of_firm.clear

    assert_equal 0, firm.clients_of_firm.size
1527
    assert_equal 0, firm.clients_of_firm.reload.size
1528 1529 1530 1531
  end

  def test_deleting_a_item_which_is_not_in_the_collection
    force_signal37_to_load_all_clients_of_firm
1532 1533 1534

    assert_predicate companies(:first_firm).clients_of_firm, :loaded?

1535
    summit = Client.find_by_name("Summit")
1536
    companies(:first_firm).clients_of_firm.delete(summit)
1537
    assert_equal 2, companies(:first_firm).clients_of_firm.size
1538
    assert_equal 2, companies(:first_firm).clients_of_firm.reload.size
1539 1540 1541
    assert_equal 2, summit.client_of
  end

1542
  def test_deleting_by_integer_id
1543
    david = Developer.find(1)
1544

1545
    assert_difference "david.projects.count", -1 do
1546 1547 1548 1549 1550 1551 1552 1553 1554
      assert_equal 1, david.projects.delete(1).size
    end

    assert_equal 1, david.projects.size
  end

  def test_deleting_by_string_id
    david = Developer.find(1)

1555 1556
    assert_difference "david.projects.count", -1 do
      assert_equal 1, david.projects.delete("1").size
1557 1558 1559
    end

    assert_equal 1, david.projects.size
1560 1561 1562 1563 1564
  end

  def test_deleting_self_type_mismatch
    david = Developer.find(1)
    david.projects.reload
1565
    assert_raise(ActiveRecord::AssociationTypeMismatch) { david.projects.delete(Project.find(1).developers) }
1566 1567
  end

1568 1569 1570
  def test_destroying
    force_signal37_to_load_all_clients_of_firm

1571 1572
    assert_predicate companies(:first_firm).clients_of_firm, :loaded?

1573 1574 1575 1576
    assert_difference "Client.count", -1 do
      companies(:first_firm).clients_of_firm.destroy(companies(:first_firm).clients_of_firm.first)
    end

1577
    assert_equal 1, companies(:first_firm).reload.clients_of_firm.size
1578
    assert_equal 1, companies(:first_firm).clients_of_firm.reload.size
1579 1580
  end

1581
  def test_destroying_by_integer_id
1582 1583
    force_signal37_to_load_all_clients_of_firm

1584 1585
    assert_predicate companies(:first_firm).clients_of_firm, :loaded?

1586 1587 1588 1589
    assert_difference "Client.count", -1 do
      companies(:first_firm).clients_of_firm.destroy(companies(:first_firm).clients_of_firm.first.id)
    end

1590
    assert_equal 1, companies(:first_firm).reload.clients_of_firm.size
1591
    assert_equal 1, companies(:first_firm).clients_of_firm.reload.size
1592 1593 1594 1595 1596
  end

  def test_destroying_by_string_id
    force_signal37_to_load_all_clients_of_firm

1597 1598
    assert_predicate companies(:first_firm).clients_of_firm, :loaded?

1599 1600 1601 1602
    assert_difference "Client.count", -1 do
      companies(:first_firm).clients_of_firm.destroy(companies(:first_firm).clients_of_firm.first.id.to_s)
    end

1603
    assert_equal 1, companies(:first_firm).reload.clients_of_firm.size
1604
    assert_equal 1, companies(:first_firm).clients_of_firm.reload.size
1605 1606
  end

1607 1608
  def test_destroying_a_collection
    force_signal37_to_load_all_clients_of_firm
1609 1610 1611

    assert_predicate companies(:first_firm).clients_of_firm, :loaded?

1612
    companies(:first_firm).clients_of_firm.create("name" => "Another Client")
1613
    assert_equal 3, companies(:first_firm).clients_of_firm.size
1614 1615 1616 1617 1618

    assert_difference "Client.count", -2 do
      companies(:first_firm).clients_of_firm.destroy([companies(:first_firm).clients_of_firm[0], companies(:first_firm).clients_of_firm[1]])
    end

1619
    assert_equal 1, companies(:first_firm).reload.clients_of_firm.size
1620
    assert_equal 1, companies(:first_firm).clients_of_firm.reload.size
1621 1622
  end

1623 1624
  def test_destroy_all
    force_signal37_to_load_all_clients_of_firm
1625 1626 1627

    assert_predicate companies(:first_firm).clients_of_firm, :loaded?

1628
    clients = companies(:first_firm).clients_of_firm.to_a
1629
    assert_not clients.empty?, "37signals has clients after load"
1630 1631
    destroyed = companies(:first_firm).clients_of_firm.destroy_all
    assert_equal clients.sort_by(&:id), destroyed.sort_by(&:id)
1632
    assert destroyed.all?(&:frozen?), "destroyed clients should be frozen"
1633
    assert companies(:first_firm).clients_of_firm.empty?, "37signals has no clients after destroy all"
1634
    assert companies(:first_firm).clients_of_firm.reload.empty?, "37signals has no clients after destroy all and refresh"
1635 1636 1637 1638
  end

  def test_dependence
    firm = companies(:first_firm)
1639
    assert_equal 3, firm.clients.size
1640
    firm.destroy
1641
    assert_empty Client.all.merge!(where: "firm_id=#{firm.id}").to_a
1642 1643
  end

1644 1645
  def test_dependence_for_associations_with_hash_condition
    david = authors(:david)
1646
    assert_difference("Post.count", -1) { assert david.destroy }
1647 1648
  end

1649
  def test_destroy_dependent_when_deleted_from_association
1650
    firm = Firm.first
1651
    assert_equal 3, firm.clients.size
1652 1653 1654 1655 1656 1657

    client = firm.clients.first
    firm.clients.delete(client)

    assert_raise(ActiveRecord::RecordNotFound) { Client.find(client.id) }
    assert_raise(ActiveRecord::RecordNotFound) { firm.clients.find(client.id) }
1658
    assert_equal 2, firm.clients.size
1659 1660 1661 1662 1663
  end

  def test_three_levels_of_dependence
    topic = Topic.create "title" => "neat and simple"
    reply = topic.replies.create "title" => "neat and simple", "content" => "still digging it"
1664
    reply.replies.create "title" => "neat and simple", "content" => "ain't complaining"
1665 1666 1667 1668 1669 1670 1671

    assert_nothing_raised { topic.destroy }
  end

  def test_dependence_with_transaction_support_on_failure
    firm = companies(:first_firm)
    clients = firm.clients
1672
    assert_equal 3, clients.length
1673
    clients.last.instance_eval { def overwrite_to_raise() raise "Trigger rollback" end }
1674 1675 1676

    firm.destroy rescue "do nothing"

1677
    assert_equal 3, Client.all.merge!(where: "firm_id=#{firm.id}").to_a.size
1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699
  end

  def test_dependence_on_account
    num_accounts = Account.count
    companies(:first_firm).destroy
    assert_equal num_accounts - 1, Account.count
  end

  def test_depends_and_nullify
    num_accounts = Account.count

    core = companies(:rails_core)
    assert_equal accounts(:rails_core_account), core.account
    assert_equal companies(:leetsoft, :jadedpixel), core.companies
    core.destroy
    assert_nil accounts(:rails_core_account).reload.firm_id
    assert_nil companies(:leetsoft).reload.client_of
    assert_nil companies(:jadedpixel).reload.client_of

    assert_equal num_accounts, Account.count
  end

1700
  def test_restrict_with_exception
1701 1702
    firm = RestrictedWithExceptionFirm.create!(name: "restrict")
    firm.companies.create(name: "child")
1703

1704
    assert_not_empty firm.companies
1705
    assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
1706 1707
    assert RestrictedWithExceptionFirm.exists?(name: "restrict")
    assert firm.companies.exists?(name: "child")
1708 1709 1710
  end

  def test_restrict_with_error
1711 1712
    firm = RestrictedWithErrorFirm.create!(name: "restrict")
    firm.companies.create(name: "child")
1713

1714
    assert_not_empty firm.companies
1715 1716 1717

    firm.destroy

1718
    assert_not_empty firm.errors
1719

1720
    assert_equal "Cannot delete record because dependent companies exist", firm.errors[:base].first
1721 1722
    assert RestrictedWithErrorFirm.exists?(name: "restrict")
    assert firm.companies.exists?(name: "child")
1723 1724
  end

1725 1726
  def test_restrict_with_error_with_locale
    I18n.backend = I18n::Backend::Simple.new
1727
    I18n.backend.store_translations "en", activerecord: { attributes: { restricted_with_error_firm: { companies: "client companies" } } }
1728 1729
    firm = RestrictedWithErrorFirm.create!(name: "restrict")
    firm.companies.create(name: "child")
1730

1731
    assert_not_empty firm.companies
1732 1733 1734

    firm.destroy

1735
    assert_not_empty firm.errors
1736 1737

    assert_equal "Cannot delete record because dependent client companies exist", firm.errors[:base].first
1738 1739
    assert RestrictedWithErrorFirm.exists?(name: "restrict")
    assert firm.companies.exists?(name: "child")
1740 1741 1742 1743
  ensure
    I18n.backend.reload!
  end

1744
  def test_included_in_collection
1745
    assert_equal true, companies(:first_firm).clients.include?(Client.find(2))
1746 1747
  end

1748
  def test_included_in_collection_for_new_records
1749
    client = Client.create(name: "Persisted")
1750
    assert_nil client.client_of
1751
    assert_equal false, Firm.new.clients_of_firm.include?(client),
1752
     "includes a client that does not belong to any firm"
1753 1754
  end

1755
  def test_adding_array_and_collection
J
Jon Leighton 已提交
1756
    assert_nothing_raised { Firm.first.clients + Firm.all.last.clients }
1757 1758 1759
  end

  def test_replace_with_less
1760
    firm = Firm.first
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
    firm.clients = [companies(:first_client)]
    assert firm.save, "Could not save firm"
    firm.reload
    assert_equal 1, firm.clients.length
  end

  def test_replace_with_less_and_dependent_nullify
    num_companies = Company.count
    companies(:rails_core).companies = []
    assert_equal num_companies, Company.count
  end

  def test_replace_with_new
1774
    firm = Firm.first
1775 1776 1777 1778
    firm.clients = [companies(:second_client), Client.new("name" => "New Client")]
    firm.save
    firm.reload
    assert_equal 2, firm.clients.length
1779
    assert_equal false, firm.clients.include?(:first_client)
1780 1781
  end

1782 1783 1784 1785 1786
  def test_replace_failure
    firm = companies(:first_firm)
    account = Account.new
    orig_accounts = firm.accounts.to_a

1787
    assert_not_predicate account, :valid?
1788
    assert_not_empty orig_accounts
1789
    error = assert_raise ActiveRecord::RecordNotSaved do
1790 1791
      firm.accounts = [account]
    end
1792

1793
    assert_equal orig_accounts, firm.accounts
1794 1795
    assert_equal "Failed to replace accounts because one or more of the " \
                 "new records could not be saved.", error.message
1796 1797
  end

1798 1799 1800 1801 1802 1803 1804 1805
  def test_replace_with_same_content
    firm = Firm.first
    firm.clients = []
    firm.save

    assert_queries(0, ignore_none: true) do
      firm.clients = []
    end
1806

1807
    assert_equal [], firm.send("clients=", [])
1808 1809
  end

1810
  def test_transactions_when_replacing_on_persisted
1811 1812
    good = Client.new(name: "Good")
    bad  = Client.new(name: "Bad", raise_on_save: true)
1813

J
Jon Leighton 已提交
1814 1815 1816 1817 1818 1819 1820
    companies(:first_firm).clients_of_firm = [good]

    begin
      companies(:first_firm).clients_of_firm = [bad]
    rescue Client::RaisedOnSave
    end

1821
    assert_equal [good], companies(:first_firm).clients_of_firm.reload
1822 1823 1824
  end

  def test_transactions_when_replacing_on_new_record
1825
    assert_no_queries(ignore_none: false) do
J
Jon Leighton 已提交
1826 1827 1828
      firm = Firm.new
      firm.clients_of_firm = [Client.new("name" => "New Client")]
    end
1829 1830
  end

1831
  def test_get_ids
1832
    assert_equal [companies(:first_client).id, companies(:second_client).id, companies(:another_first_firm_client).id], companies(:first_firm).client_ids
1833 1834
  end

1835 1836
  def test_get_ids_for_loaded_associations
    company = companies(:first_firm)
1837
    company.clients.reload
1838 1839 1840 1841 1842 1843 1844 1845
    assert_queries(0) do
      company.client_ids
      company.client_ids
    end
  end

  def test_get_ids_for_unloaded_associations_does_not_load_them
    company = companies(:first_firm)
1846
    assert_not_predicate company.clients, :loaded?
1847
    assert_equal [companies(:first_client).id, companies(:second_client).id, companies(:another_first_firm_client).id], company.client_ids
1848
    assert_not_predicate company.clients, :loaded?
1849 1850
  end

1851 1852 1853 1854 1855
  def test_counter_cache_on_unloaded_association
    car = Car.create(name: "My AppliCar")
    assert_equal car.engines.size, 0
  end

1856 1857 1858 1859
  def test_get_ids_ignores_include_option
    assert_equal [readers(:michael_welcome).id], posts(:welcome).readers_with_person_ids
  end

1860
  def test_get_ids_for_ordered_association
1861
    assert_equal [companies(:another_first_firm_client).id, companies(:second_client).id, companies(:first_client).id], companies(:first_firm).clients_ordered_by_name_ids
1862 1863
  end

1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878
  def test_get_ids_for_association_on_new_record_does_not_try_to_find_records
    Company.columns  # Load schema information so we don't query below
    Contract.columns # if running just this test.

    company = Company.new
    assert_queries(0) do
      company.contract_ids
    end

    assert_equal [], company.contract_ids
  end

  def test_set_ids_for_association_on_new_record_applies_association_correctly
    contract_a = Contract.create!
    contract_b = Contract.create!
1879
    Contract.create! # another contract
1880
    company = Company.new(name: "Some Company")
1881 1882 1883 1884 1885 1886 1887 1888 1889 1890

    company.contract_ids = [contract_a.id, contract_b.id]
    assert_equal [contract_a.id, contract_b.id], company.contract_ids
    assert_equal [contract_a, contract_b], company.contracts

    company.save!
    assert_equal company, contract_a.reload.company
    assert_equal company, contract_b.reload.company
  end

1891
  def test_assign_ids_ignoring_blanks
1892
    firm = Firm.create!(name: "Apple")
1893
    firm.client_ids = [companies(:first_client).id, nil, companies(:second_client).id, ""]
1894 1895
    firm.save!

1896
    assert_equal 2, firm.clients.reload.size
1897
    assert_equal true, firm.clients.include?(companies(:second_client))
1898 1899 1900 1901 1902 1903 1904 1905 1906 1907
  end

  def test_get_ids_for_through
    assert_equal [comments(:eager_other_comment1).id], authors(:mary).comment_ids
  end

  def test_modifying_a_through_a_has_many_should_raise
    [
      lambda { authors(:mary).comment_ids = [comments(:greetings).id, comments(:more_greetings).id] },
      lambda { authors(:mary).comments = [comments(:greetings), comments(:more_greetings)] },
1908
      lambda { authors(:mary).comments << Comment.create!(body: "Yay", post_id: 424242) },
1909
      lambda { authors(:mary).comments.delete(authors(:mary).comments.first) },
1910
    ].each { |block| assert_raise(ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection, &block) }
1911 1912
  end

1913 1914 1915 1916 1917 1918 1919
  def test_associations_order_should_be_priority_over_throughs_order
    david = authors(:david)
    expected = [12, 10, 9, 8, 7, 6, 5, 3, 2, 1]
    assert_equal expected, david.comments_desc.map(&:id)
    assert_equal expected, Author.includes(:comments_desc).find(david.id).comments_desc.map(&:id)
  end

1920
  def test_dynamic_find_should_respect_association_order_for_through
1921
    assert_equal Comment.find(10), authors(:david).comments_desc.where("comments.type = 'SpecialComment'").first
1922
    assert_equal Comment.find(10), authors(:david).comments_desc.find_by_type("SpecialComment")
1923 1924 1925 1926 1927 1928 1929 1930 1931
  end

  def test_has_many_through_respects_hash_conditions
    assert_equal authors(:david).hello_posts, authors(:david).hello_posts_with_hash_conditions
    assert_equal authors(:david).hello_post_comments, authors(:david).hello_post_comments_with_hash_conditions
  end

  def test_include_uses_array_include_after_loaded
    firm = companies(:first_firm)
J
Jon Leighton 已提交
1932
    firm.clients.load_target
1933

1934 1935 1936
    client = firm.clients.first

    assert_no_queries do
1937
      assert_predicate firm.clients, :loaded?
1938
      assert_equal true, firm.clients.include?(client)
1939 1940 1941 1942 1943 1944 1945 1946
    end
  end

  def test_include_checks_if_record_exists_if_target_not_loaded
    firm = companies(:first_firm)
    client = firm.clients.first

    firm.reload
D
Daniel Colson 已提交
1947
    assert_not_predicate firm.clients, :loaded?
1948
    assert_queries(1) do
1949
      assert_equal true, firm.clients.include?(client)
1950
    end
D
Daniel Colson 已提交
1951
    assert_not_predicate firm.clients, :loaded?
1952 1953 1954 1955
  end

  def test_include_returns_false_for_non_matching_record_to_verify_scoping
    firm = companies(:first_firm)
1956
    client = Client.create!(name: "Not Associated")
1957

D
Daniel Colson 已提交
1958
    assert_not_predicate firm.clients, :loaded?
1959
    assert_equal false, firm.clients.include?(client)
1960 1961
  end

1962
  def test_calling_first_nth_or_last_on_association_should_not_load_association
1963 1964
    firm = companies(:first_firm)
    firm.clients.first
1965
    firm.clients.second
1966
    firm.clients.last
1967
    assert_not_predicate firm.clients, :loaded?
1968 1969 1970 1971
  end

  def test_calling_first_or_last_on_loaded_association_should_not_fetch_with_query
    firm = companies(:first_firm)
J
Jon Leighton 已提交
1972
    firm.clients.load_target
1973
    assert_predicate firm.clients, :loaded?
1974

1975
    assert_no_queries(ignore_none: false) do
1976 1977 1978 1979 1980 1981 1982 1983 1984
      firm.clients.first
      assert_equal 2, firm.clients.first(2).size
      firm.clients.last
      assert_equal 2, firm.clients.last(2).size
    end
  end

  def test_calling_first_or_last_on_existing_record_with_build_should_load_association
    firm = companies(:first_firm)
1985
    firm.clients.build(name: "Foo")
1986
    assert_not_predicate firm.clients, :loaded?
1987 1988 1989

    assert_queries 1 do
      firm.clients.first
1990
      firm.clients.second
1991 1992 1993
      firm.clients.last
    end

1994
    assert_predicate firm.clients, :loaded?
1995 1996
  end

1997
  def test_calling_first_nth_or_last_on_existing_record_with_create_should_not_load_association
1998
    firm = companies(:first_firm)
1999
    firm.clients.create(name: "Foo")
2000
    assert_not_predicate firm.clients, :loaded?
2001

2002
    assert_queries 3 do
2003
      firm.clients.first
2004
      firm.clients.second
2005 2006 2007
      firm.clients.last
    end

2008
    assert_not_predicate firm.clients, :loaded?
2009 2010
  end

2011
  def test_calling_first_nth_or_last_on_new_record_should_not_run_queries
2012 2013 2014 2015
    firm = Firm.new

    assert_no_queries do
      firm.clients.first
2016
      firm.clients.second
2017 2018 2019
      firm.clients.last
    end
  end
2020

2021
  def test_calling_first_or_last_with_integer_on_association_should_not_load_association
2022
    firm = companies(:first_firm)
2023
    firm.clients.create(name: "Foo")
2024
    assert_not_predicate firm.clients, :loaded?
2025

2026
    assert_queries 2 do
2027 2028 2029 2030
      firm.clients.first(2)
      firm.clients.last(2)
    end

2031
    assert_not_predicate firm.clients, :loaded?
2032 2033
  end

2034 2035 2036 2037 2038
  def test_calling_many_should_count_instead_of_loading_association
    firm = companies(:first_firm)
    assert_queries(1) do
      firm.clients.many?  # use count query
    end
2039
    assert_not_predicate firm.clients, :loaded?
2040 2041 2042 2043
  end

  def test_calling_many_on_loaded_association_should_not_use_query
    firm = companies(:first_firm)
2044
    firm.clients.load  # force load
2045 2046 2047 2048 2049 2050
    assert_no_queries { assert firm.clients.many? }
  end

  def test_calling_many_should_defer_to_collection_if_using_a_block
    firm = companies(:first_firm)
    assert_queries(1) do
U
utilum 已提交
2051 2052 2053
      assert_not_called(firm.clients, :size) do
        firm.clients.many? { true }
      end
2054
    end
2055
    assert_predicate firm.clients, :loaded?
2056 2057 2058 2059
  end

  def test_calling_many_should_return_false_if_none_or_one
    firm = companies(:another_firm)
2060
    assert_not_predicate firm.clients_like_ms, :many?
2061 2062 2063
    assert_equal 0, firm.clients_like_ms.size

    firm = companies(:first_firm)
2064
    assert_not_predicate firm.limited_clients, :many?
2065 2066 2067 2068 2069
    assert_equal 1, firm.limited_clients.size
  end

  def test_calling_many_should_return_true_if_more_than_one
    firm = companies(:first_firm)
2070
    assert_predicate firm.clients, :many?
2071
    assert_equal 3, firm.clients.size
2072 2073
  end

2074 2075 2076 2077 2078
  def test_calling_none_should_count_instead_of_loading_association
    firm = companies(:first_firm)
    assert_queries(1) do
      firm.clients.none?  # use count query
    end
2079
    assert_not_predicate firm.clients, :loaded?
2080 2081 2082 2083
  end

  def test_calling_none_on_loaded_association_should_not_use_query
    firm = companies(:first_firm)
2084
    firm.clients.load  # force load
2085
    assert_no_queries { assert_not firm.clients.none? }
2086 2087 2088 2089 2090
  end

  def test_calling_none_should_defer_to_collection_if_using_a_block
    firm = companies(:first_firm)
    assert_queries(1) do
U
utilum 已提交
2091 2092 2093
      assert_not_called(firm.clients, :size) do
        firm.clients.none? { true }
      end
2094
    end
2095
    assert_predicate firm.clients, :loaded?
2096 2097 2098 2099
  end

  def test_calling_none_should_return_true_if_none
    firm = companies(:another_firm)
2100
    assert_predicate firm.clients_like_ms, :none?
2101 2102 2103 2104 2105
    assert_equal 0, firm.clients_like_ms.size
  end

  def test_calling_none_should_return_false_if_any
    firm = companies(:first_firm)
2106
    assert_not_predicate firm.limited_clients, :none?
2107 2108 2109 2110 2111 2112 2113 2114
    assert_equal 1, firm.limited_clients.size
  end

  def test_calling_one_should_count_instead_of_loading_association
    firm = companies(:first_firm)
    assert_queries(1) do
      firm.clients.one?  # use count query
    end
2115
    assert_not_predicate firm.clients, :loaded?
2116 2117 2118 2119
  end

  def test_calling_one_on_loaded_association_should_not_use_query
    firm = companies(:first_firm)
2120
    firm.clients.load  # force load
2121
    assert_no_queries { assert_not firm.clients.one? }
2122 2123 2124 2125 2126
  end

  def test_calling_one_should_defer_to_collection_if_using_a_block
    firm = companies(:first_firm)
    assert_queries(1) do
U
utilum 已提交
2127 2128 2129
      assert_not_called(firm.clients, :size) do
        firm.clients.one? { true }
      end
2130
    end
2131
    assert_predicate firm.clients, :loaded?
2132 2133 2134 2135
  end

  def test_calling_one_should_return_false_if_zero
    firm = companies(:another_firm)
D
Daniel Colson 已提交
2136
    assert_not_predicate firm.clients_like_ms, :one?
2137 2138 2139 2140 2141
    assert_equal 0, firm.clients_like_ms.size
  end

  def test_calling_one_should_return_true_if_one
    firm = companies(:first_firm)
2142
    assert_predicate firm.limited_clients, :one?
2143 2144 2145 2146 2147
    assert_equal 1, firm.limited_clients.size
  end

  def test_calling_one_should_return_false_if_more_than_one
    firm = companies(:first_firm)
D
Daniel Colson 已提交
2148
    assert_not_predicate firm.clients, :one?
2149 2150 2151
    assert_equal 3, firm.clients.size
  end

2152 2153 2154 2155
  def test_joins_with_namespaced_model_should_use_correct_type
    old = ActiveRecord::Base.store_full_sti_class
    ActiveRecord::Base.store_full_sti_class = true

2156 2157
    firm = Namespaced::Firm.create(name: "Some Company")
    firm.clients.create(name: "Some Client")
2158

2159
    stats = Namespaced::Firm.all.merge!(
2160 2161 2162
      select: "#{Namespaced::Firm.table_name}.id, COUNT(#{Namespaced::Client.table_name}.id) AS num_clients",
      joins: :clients,
      group: "#{Namespaced::Firm.table_name}.id"
J
Jon Leighton 已提交
2163
    ).find firm.id
2164 2165 2166 2167 2168
    assert_equal 1, stats.num_clients.to_i
  ensure
    ActiveRecord::Base.store_full_sti_class = old
  end

2169
  def test_association_proxy_transaction_method_starts_transaction_in_association_class
U
utilum 已提交
2170 2171 2172 2173
    assert_called(Comment, :transaction) do
      Post.first.comments.transaction do
        # nothing
      end
2174 2175 2176
    end
  end

2177
  def test_sending_new_to_association_proxy_should_have_same_effect_as_calling_new
2178 2179 2180 2181
    client_association = companies(:first_firm).clients
    assert_equal client_association.new.attributes, client_association.send(:new).attributes
  end

2182
  def test_creating_using_primary_key
2183
    firm = Firm.first
2184
    client = firm.clients_using_primary_key.create!(name: "test")
2185 2186
    assert_equal firm.name, client.firm_name
  end
2187 2188

  def test_defining_has_many_association_with_delete_all_dependency_lazily_evaluates_target_class
2189 2190 2191 2192 2193 2194 2195 2196 2197 2198
    assert_not_called_on_instance_of(
      ActiveRecord::Reflection::AssociationReflection,
      :class_name,
    ) do
      class_eval(<<-EOF, __FILE__, __LINE__ + 1)
        class DeleteAllModel < ActiveRecord::Base
          has_many :nonentities, :dependent => :delete_all
        end
      EOF
    end
2199 2200 2201
  end

  def test_defining_has_many_association_with_nullify_dependency_lazily_evaluates_target_class
2202 2203 2204 2205 2206 2207 2208 2209 2210 2211
    assert_not_called_on_instance_of(
      ActiveRecord::Reflection::AssociationReflection,
      :class_name,
    ) do
      class_eval(<<-EOF, __FILE__, __LINE__ + 1)
        class NullifyModel < ActiveRecord::Base
          has_many :nonentities, :dependent => :nullify
        end
      EOF
    end
2212
  end
2213 2214

  def test_attributes_are_being_set_when_initialized_from_has_many_association_with_where_clause
2215
    new_comment = posts(:welcome).comments.where(body: "Some content").build
2216 2217 2218 2219
    assert_equal new_comment.body, "Some content"
  end

  def test_attributes_are_being_set_when_initialized_from_has_many_association_with_multiple_where_clauses
2220
    new_comment = posts(:welcome).comments.where(body: "Some content").where(type: "SpecialComment").build
2221 2222 2223 2224
    assert_equal new_comment.body, "Some content"
    assert_equal new_comment.type, "SpecialComment"
    assert_equal new_comment.post_id, posts(:welcome).id
  end
2225 2226 2227 2228

  def test_include_method_in_has_many_association_should_return_true_for_instance_added_with_build
    post = Post.new
    comment = post.comments.build
2229
    assert_equal true, post.comments.include?(comment)
2230
  end
2231 2232 2233

  def test_load_target_respects_protected_attributes
    topic = Topic.create!
2234
    reply = topic.replies.create(title: "reply 1")
2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251
    reply.approved = false
    reply.save!

    # Save with a different object instance, so the instance that's still held
    # in topic.relies doesn't know about the changed attribute.
    reply2 = Reply.find(reply.id)
    reply2.approved = true
    reply2.save!

    # Force loading the collection from the db. This will merge the existing
    # object (reply) with what gets loaded from the db (which includes the
    # changed approved attribute). approved is a protected attribute, so if mass
    # assignment is used, it won't get updated and will still be false.
    first = topic.replies.to_a.first
    assert_equal reply.id, first.id
    assert_equal true, first.approved?
  end
2252 2253 2254 2255 2256 2257 2258

  def test_to_a_should_dup_target
    ary    = topics(:first).replies.to_a
    target = topics(:first).replies.target

    assert_not_equal target.object_id, ary.object_id
  end
2259 2260

  def test_merging_with_custom_attribute_writer
2261
    bulb = Bulb.new(color: "red")
2262 2263 2264 2265 2266 2267 2268
    assert_equal "RED!", bulb.color

    car = Car.create!
    car.bulbs << bulb

    assert_equal "RED!", car.bulbs.to_a.first.color
  end
2269

2270
  def test_abstract_class_with_polymorphic_has_many
2271 2272
    post = SubStiPost.create! title: "fooo", body: "baa"
    tagging = Tagging.create! taggable: post
2273 2274
    assert_equal [tagging], post.taggings
  end
F
Farley Knight 已提交
2275

2276
  def test_with_polymorphic_has_many_with_custom_columns_name
2277
    post = Post.create! title: "foo", body: "bar"
2278 2279 2280 2281 2282 2283 2284
    image = Image.create!

    post.images << image

    assert_equal [image], post.images
  end

A
Andy Lindeman 已提交
2285
  def test_build_with_polymorphic_has_many_does_not_allow_to_override_type_and_id
2286
    welcome = posts(:welcome)
2287
    tagging = welcome.taggings.build(taggable_id: 99, taggable_type: "ShouldNotChange")
2288 2289

    assert_equal welcome.id, tagging.taggable_id
2290
    assert_equal "Post", tagging.taggable_type
2291 2292
  end

2293 2294 2295 2296 2297 2298 2299
  def test_build_from_polymorphic_association_sets_inverse_instance
    post = Post.new
    tagging = post.taggings.build

    assert_equal post, tagging.taggable
  end

F
Farley Knight 已提交
2300 2301 2302 2303 2304 2305 2306
  def test_dont_call_save_callbacks_twice_on_has_many
    firm = companies(:first_firm)
    contract = firm.contracts.create!

    assert_equal 1, contract.hi_count
    assert_equal 1, contract.bye_count
  end
2307 2308

  def test_association_attributes_are_available_to_after_initialize
2309
    car = Car.create(name: "honda")
2310 2311
    bulb = car.bulbs.build

2312
    assert_equal car.id, bulb.attributes_after_initialize["car_id"]
2313
  end
2314

2315
  def test_attributes_are_set_when_initialized_from_has_many_null_relationship
2316 2317 2318
    car  = Car.new name: "honda"
    bulb = car.bulbs.where(name: "headlight").first_or_initialize
    assert_equal "headlight", bulb.name
2319 2320 2321
  end

  def test_attributes_are_set_when_initialized_from_polymorphic_has_many_null_relationship
2322 2323
    post    = Post.new title: "title", body: "bar"
    tag     = Tag.create!(name: "foo")
2324 2325 2326 2327

    tagging = post.taggings.where(tag: tag).first_or_initialize

    assert_equal tag.id, tagging.tag_id
2328
    assert_equal "Post", tagging.taggable_type
2329 2330
  end

2331
  def test_replace
2332
    car = Car.create(name: "honda")
2333 2334 2335 2336 2337 2338 2339 2340
    bulb1 = car.bulbs.create
    bulb2 = Bulb.create

    assert_equal [bulb1], car.bulbs
    car.bulbs.replace([bulb2])
    assert_equal [bulb2], car.bulbs
    assert_equal [bulb2], car.reload.bulbs
  end
2341

2342
  def test_replace_returns_target
2343
    car = Car.create(name: "honda")
2344 2345 2346 2347 2348
    bulb1 = car.bulbs.create
    bulb2 = car.bulbs.create
    bulb3 = Bulb.create

    assert_equal [bulb1, bulb2], car.bulbs
2349
    result = car.bulbs.replace([bulb3, bulb1])
2350 2351 2352 2353
    assert_equal [bulb1, bulb3], car.bulbs
    assert_equal [bulb1, bulb3], result
  end

2354 2355 2356 2357
  def test_collection_association_with_private_kernel_method
    firm = companies(:first_firm)
    assert_equal [accounts(:signals37)], firm.accounts.open
  end
J
Jon Leighton 已提交
2358 2359

  test "first_or_initialize adds the record to the association" do
2360
    firm = Firm.create! name: "omg"
J
Jon Leighton 已提交
2361 2362 2363 2364 2365
    client = firm.clients_of_firm.first_or_initialize
    assert_equal [client], firm.clients_of_firm
  end

  test "first_or_create adds the record to the association" do
2366
    firm = Firm.create! name: "omg"
J
Jon Leighton 已提交
2367
    firm.clients_of_firm.load_target
2368
    client = firm.clients_of_firm.first_or_create name: "lol"
J
Jon Leighton 已提交
2369 2370 2371
    assert_equal [client], firm.clients_of_firm
    assert_equal [client], firm.reload.clients_of_firm
  end
2372 2373 2374 2375 2376

  test "delete_all, when not loaded, doesn't load the records" do
    post = posts(:welcome)

    assert post.taggings_with_delete_all.count > 0
2377
    assert_not_predicate post.taggings_with_delete_all, :loaded?
2378 2379 2380 2381 2382 2383

    # 2 queries: one DELETE and another to update the counter cache
    assert_queries(2) do
      post.taggings_with_delete_all.delete_all
    end
  end
2384

2385 2386 2387
  test "has many associations on new records use null relations" do
    post = Post.new

2388
    assert_no_queries(ignore_none: false) do
2389
      assert_equal [], post.comments
2390
      assert_equal [], post.comments.where(body: "omg")
2391
      assert_equal [], post.comments.pluck(:body)
2392
      assert_equal 0,  post.comments.sum(:id)
V
Vipul A M 已提交
2393
      assert_equal 0,  post.comments.count
2394 2395
    end
  end
2396 2397 2398

  test "collection proxy respects default scope" do
    author = authors(:mary)
2399
    assert_not_predicate author.first_posts, :exists?
2400
  end
J
Jon Leighton 已提交
2401 2402 2403 2404 2405 2406 2407 2408 2409 2410

  test "association with extend option" do
    post = posts(:welcome)
    assert_equal "lifo",  post.comments_with_extend.author
    assert_equal "hello", post.comments_with_extend.greeting
  end

  test "association with extend option with multiple extensions" do
    post = posts(:welcome)
    assert_equal "lifo",  post.comments_with_extend_2.author
2411 2412 2413 2414 2415 2416 2417 2418 2419
    assert_equal "hullo", post.comments_with_extend_2.greeting
  end

  test "extend option affects per association" do
    post = posts(:welcome)
    assert_equal "lifo",  post.comments_with_extend.author
    assert_equal "lifo",  post.comments_with_extend_2.author
    assert_equal "hello", post.comments_with_extend.greeting
    assert_equal "hullo", post.comments_with_extend_2.greeting
J
Jon Leighton 已提交
2420
  end
2421 2422 2423 2424 2425

  test "delete record with complex joins" do
    david = authors(:david)

    post = david.posts.first
2426
    post.type = "PostWithSpecialCategorization"
2427 2428 2429 2430 2431 2432 2433 2434 2435 2436
    post.save

    categorization = post.categorizations.first
    categorization.special = true
    categorization.save

    assert_not_equal [], david.posts_with_special_categorizations
    david.posts_with_special_categorizations = []
    assert_equal [], david.posts_with_special_categorizations
  end
2437 2438

  test "does not duplicate associations when used with natural primary keys" do
2439
    speedometer = Speedometer.create!(id: "4")
2440
    speedometer.minivans.create!(minivan_id: "a-van-red", name: "a van", color: "red")
2441 2442 2443 2444

    assert_equal 1, speedometer.minivans.to_a.size, "Only one association should be present:\n#{speedometer.minivans.to_a}"
    assert_equal 1, speedometer.reload.minivans.to_a.size
  end
J
Jon Leighton 已提交
2445 2446 2447 2448 2449 2450 2451 2452 2453

  test "can unscope the default scope of the associated model" do
    car = Car.create!
    bulb1 = Bulb.create! name: "defaulty", car: car
    bulb2 = Bulb.create! name: "other",    car: car

    assert_equal [bulb1], car.bulbs
    assert_equal [bulb1, bulb2], car.all_bulbs.sort_by(&:id)
  end
2454

2455
  test "can unscope and where the default scope of the associated model" do
2456
    Car.has_many :other_bulbs, -> { unscope(where: [:name]).where(name: "other") }, class_name: "Bulb"
2457 2458 2459 2460 2461 2462 2463 2464 2465
    car = Car.create!
    bulb1 = Bulb.create! name: "defaulty", car: car
    bulb2 = Bulb.create! name: "other",    car: car

    assert_equal [bulb1], car.bulbs
    assert_equal [bulb2], car.other_bulbs
  end

  test "can rewhere the default scope of the associated model" do
2466
    Car.has_many :old_bulbs, -> { rewhere(name: "old") }, class_name: "Bulb"
2467 2468 2469 2470 2471 2472 2473 2474
    car = Car.create!
    bulb1 = Bulb.create! name: "defaulty", car: car
    bulb2 = Bulb.create! name: "old",      car: car

    assert_equal [bulb1], car.bulbs
    assert_equal [bulb2], car.old_bulbs
  end

2475
  test "unscopes the default scope of associated model when used with include" do
2476 2477 2478
    car = Car.create!
    bulb = Bulb.create! name: "other", car: car

2479 2480 2481
    assert_equal [bulb], Car.find(car.id).all_bulbs
    assert_equal [bulb], Car.includes(:all_bulbs).find(car.id).all_bulbs
    assert_equal [bulb], Car.eager_load(:all_bulbs).find(car.id).all_bulbs
2482 2483
  end

2484 2485 2486 2487
  test "raises RecordNotDestroyed when replaced child can't be destroyed" do
    car = Car.create!
    original_child = FailedBulb.create!(car: car)

2488
    error = assert_raise(ActiveRecord::RecordNotDestroyed) do
2489 2490 2491 2492
      car.failed_bulbs = [FailedBulb.create!]
    end

    assert_equal [original_child], car.reload.failed_bulbs
2493
    assert_equal "Failed to destroy the record", error.message
2494
  end
2495

2496
  test "updates counter cache when default scope is given" do
2497 2498 2499 2500 2501
    topic = DefaultRejectedTopic.create approved: true

    assert_difference "topic.reload.replies_count", 1 do
      topic.approved_replies.create!
    end
2502
  end
2503

2504 2505
  test "dangerous association name raises ArgumentError" do
    [:errors, "errors", :save, "save"].each do |name|
2506 2507 2508 2509 2510 2511 2512
      assert_raises(ArgumentError, "Association #{name} should not be allowed") do
        Class.new(ActiveRecord::Base) do
          has_many name
        end
      end
    end
  end
2513

2514
  test "passes custom context validation to validate children" do
2515 2516
    pirate = FamousPirate.new
    pirate.famous_ships << ship = FamousShip.new
2517

2518
    assert_predicate pirate, :valid?
2519
    assert_not pirate.valid?(:conference)
2520 2521
    assert_equal "can't be blank", ship.errors[:name].first
  end
2522

2523
  test "association with instance dependent scope" do
2524 2525 2526 2527 2528 2529 2530 2531
    bob = authors(:bob)
    Post.create!(title: "signed post by bob", body: "stuff", author: authors(:bob))
    Post.create!(title: "anonymous post", body: "more stuff", author: authors(:bob))
    assert_equal ["misc post by bob", "other post by bob",
                  "signed post by bob"], bob.posts_with_signature.map(&:title).sort

    assert_equal [], authors(:david).posts_with_signature.map(&:title)
  end
2532

2533
  test "associations autosaves when object is already persisted" do
2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544
    bulb = Bulb.create!
    tyre = Tyre.create!

    car = Car.create! do |c|
      c.bulbs << bulb
      c.tyres << tyre
    end

    assert_equal 1, car.bulbs.count
    assert_equal 1, car.tyres.count
  end
2545

2546
  test "associations replace in memory when records have the same id" do
2547 2548 2549 2550 2551 2552 2553 2554 2555 2556
    bulb = Bulb.create!
    car = Car.create!(bulbs: [bulb])

    new_bulb = Bulb.find(bulb.id)
    new_bulb.name = "foo"
    car.bulbs = [new_bulb]

    assert_equal "foo", car.bulbs.first.name
  end

2557
  test "in memory replacement executes no queries" do
2558 2559 2560 2561 2562 2563 2564 2565 2566 2567
    bulb = Bulb.create!
    car = Car.create!(bulbs: [bulb])

    new_bulb = Bulb.find(bulb.id)

    assert_no_queries do
      car.bulbs = [new_bulb]
    end
  end

2568
  test "in memory replacements do not execute callbacks" do
2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588
    raise_after_add = false
    klass = Class.new(ActiveRecord::Base) do
      self.table_name = :cars
      has_many :bulbs, after_add: proc { raise if raise_after_add }

      def self.name
        "Car"
      end
    end
    bulb = Bulb.create!
    car = klass.create!(bulbs: [bulb])

    new_bulb = Bulb.find(bulb.id)
    raise_after_add = true

    assert_nothing_raised do
      car.bulbs = [new_bulb]
    end
  end

2589
  test "in memory replacements sets inverse instance" do
2590 2591 2592 2593 2594 2595 2596 2597 2598
    bulb = Bulb.create!
    car = Car.create!(bulbs: [bulb])

    new_bulb = Bulb.find(bulb.id)
    car.bulbs = [new_bulb]

    assert_same car, new_bulb.car
  end

2599 2600 2601 2602 2603 2604 2605 2606 2607
  test "reattach to new objects replaces inverse association and foreign key" do
    bulb = Bulb.create!(car: Car.create!)
    assert bulb.car_id
    car = Car.new
    car.bulbs << bulb
    assert_equal car, bulb.car
    assert_nil bulb.car_id
  end

2608
  test "in memory replacement maintains order" do
2609 2610 2611 2612 2613 2614 2615 2616 2617
    first_bulb = Bulb.create!
    second_bulb = Bulb.create!
    car = Car.create!(bulbs: [first_bulb, second_bulb])

    same_bulb = Bulb.find(first_bulb.id)
    car.bulbs = [second_bulb, same_bulb]

    assert_equal [first_bulb, second_bulb], car.bulbs
  end
2618

2619 2620 2621 2622 2623 2624 2625 2626
  test "association size calculation works with default scoped selects when not previously fetched" do
    firm = Firm.create!(name: "Firm")
    5.times { firm.developers_with_select << Developer.create!(name: "Developer") }

    same_firm = Firm.find(firm.id)
    assert_equal 5, same_firm.developers_with_select.size
  end

2627
  test "prevent double insertion of new object when the parent association loaded in the after save callback" do
2628
    reset_callbacks(:save, Bulb) do
2629
      Bulb.after_save { |record| record.car.bulbs.load }
2630

2631 2632
      car = Car.create!
      car.bulbs << Bulb.new
2633

2634 2635
      assert_equal 1, car.bulbs.size
    end
2636 2637
  end

2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649
  test "prevent double firing the before save callback of new object when the parent association saved in the callback" do
    reset_callbacks(:save, Bulb) do
      count = 0
      Bulb.before_save { |record| record.car.save && count += 1 }

      car = Car.create!
      car.bulbs.create!

      assert_equal 1, count
    end
  end

2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713
  test "calling size on an association that has not been loaded performs a query" do
    car = Car.create!
    Bulb.create(car_id: car.id)

    car_two = Car.create!

    assert_queries(1) do
      assert_equal 1, car.bulbs.size
    end

    assert_queries(1) do
      assert_equal 0, car_two.bulbs.size
    end
  end

  test "calling size on an association that has been loaded does not perform query" do
    car = Car.create!
    Bulb.create(car_id: car.id)
    car.bulb_ids

    car_two = Car.create!
    car_two.bulb_ids

    assert_no_queries do
      assert_equal 1, car.bulbs.size
    end

    assert_no_queries do
      assert_equal 0, car_two.bulbs.size
    end
  end

  test "calling empty on an association that has not been loaded performs a query" do
    car = Car.create!
    Bulb.create(car_id: car.id)

    car_two = Car.create!

    assert_queries(1) do
      assert_not_empty car.bulbs
    end

    assert_queries(1) do
      assert_empty car_two.bulbs
    end
  end

  test "calling empty on an association that has been loaded does not performs query" do
    car = Car.create!
    Bulb.create(car_id: car.id)
    car.bulb_ids

    car_two = Car.create!
    car_two.bulb_ids

    assert_no_queries do
      assert_not_empty car.bulbs
    end

    assert_no_queries do
      assert_empty car_two.bulbs
    end
  end

2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742
  class AuthorWithErrorDestroyingAssociation < ActiveRecord::Base
    self.table_name = "authors"
    has_many :posts_with_error_destroying,
      class_name: "PostWithErrorDestroying",
      foreign_key: :author_id,
      dependent: :destroy
  end

  class PostWithErrorDestroying < ActiveRecord::Base
    self.table_name = "posts"
    self.inheritance_column = nil
    before_destroy -> { throw :abort }
  end

  def test_destroy_does_not_raise_when_association_errors_on_destroy
    assert_no_difference "AuthorWithErrorDestroyingAssociation.count" do
      author = AuthorWithErrorDestroyingAssociation.first

      assert_not author.destroy
    end
  end

  def test_destroy_with_bang_bubbles_errors_from_associations
    error = assert_raises ActiveRecord::RecordNotDestroyed do
      AuthorWithErrorDestroyingAssociation.first.destroy!
    end

    assert_instance_of PostWithErrorDestroying, error.record
  end
2743 2744

  def test_ids_reader_memoization
2745
    car = Car.create!(name: "Tofaş")
2746 2747 2748 2749
    bulb = Bulb.create!(car: car)

    assert_equal [bulb.id], car.bulb_ids
    assert_no_queries { car.bulb_ids }
2750 2751 2752 2753 2754

    bulb2 = car.bulbs.create!

    assert_equal [bulb.id, bulb2.id], car.bulb_ids
    assert_no_queries { car.bulb_ids }
2755
  end
2756

2757 2758
  def test_loading_association_in_validate_callback_doesnt_affect_persistence
    reset_callbacks(:validation, Bulb) do
2759
      Bulb.after_validation { |record| record.car.bulbs.load }
2760 2761 2762 2763 2764 2765 2766 2767

      car = Car.create!(name: "Car")
      bulb = car.bulbs.create!

      assert_equal [bulb], car.bulbs
    end
  end

2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778
  def test_create_children_could_be_rolled_back_by_after_save
    firm = Firm.create!(name: "A New Firm, Inc")
    assert_no_difference "Client.count" do
      client = firm.clients.create(name: "New Client") do |cli|
        cli.rollback_on_save = true
        assert_not cli.rollback_on_create_called
      end
      assert client.rollback_on_create_called
    end
  end

2779 2780 2781 2782 2783
  private

    def force_signal37_to_load_all_clients_of_firm
      companies(:first_firm).clients_of_firm.load_target
    end
2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797

    def reset_callbacks(kind, klass)
      old_callbacks = {}
      old_callbacks[klass] = klass.send("_#{kind}_callbacks").dup
      klass.subclasses.each do |subclass|
        old_callbacks[subclass] = subclass.send("_#{kind}_callbacks").dup
      end
      yield
    ensure
      klass.send("_#{kind}_callbacks=", old_callbacks[klass])
      klass.subclasses.each do |subclass|
        subclass.send("_#{kind}_callbacks=", old_callbacks[subclass])
      end
    end
2798
end