has_many_associations_test.rb 81.5 KB
Newer Older
1
require "cases/helper"
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
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/job"
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"
41

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

  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
49
    assert author.posts_with_comments_sorted_by_comment_id.where("comments.id > 0").reorder("posts.comments_count DESC", "posts.tags_count DESC").last
50 51
  end
end
52

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

  def test_custom_primary_key_on_new_record_should_fetch_with_query
57
    subscriber = Subscriber.new(nick: "webster132")
58 59 60 61 62 63
    assert !subscriber.subscriptions.loaded?

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

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

  def test_association_primary_key_on_new_record_should_fetch_with_query
68
    author = Author.new(name: "David")
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
    assert !author.essays.loaded?

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

    assert_equal author.essays, Essay.where(writer_id: "David")
  end

  def test_has_many_custom_primary_key
    david = authors(:david)
    assert_equal david.essays, Essay.where(writer_id: "David")
  end

  def test_has_many_assignment_with_custom_primary_key
    david = people(:david)

    assert_equal ["A Modest Proposal"], david.essays.map(&:name)
87
    david.essays = [Essay.create!(name: "Remote Work")]
88 89 90 91 92 93 94 95 96 97 98 99
    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
    assert !author.essays.loaded?

    assert_queries 0 do
      assert_equal 0, author.essays.size
    end
  end
end
100 101 102

class HasManyAssociationsTest < ActiveRecord::TestCase
  fixtures :accounts, :categories, :companies, :developers, :projects,
103
           :developers_projects, :topics, :authors, :comments,
104
           :posts, :readers, :taggings, :cars, :jobs, :tags,
105
           :categorizations, :zines, :interests
106 107 108 109 110

  def setup
    Client.destroyed_client_ids.clear
  end

111 112 113 114 115 116
  def test_sti_subselect_count
    tag = Tag.first
    len = Post.tagged_with(tag.id).limit(10).size
    assert_operator len, :>, 0
  end

117 118
  def test_anonymous_has_many
    developer = Class.new(ActiveRecord::Base) {
119
      self.table_name = "developers"
120 121 122
      dev = self

      developer_project = Class.new(ActiveRecord::Base) {
123
        self.table_name = "developers_projects"
124
        belongs_to :developer, anonymous_class: dev
125
      }
126
      has_many :developer_projects, anonymous_class: developer_project, foreign_key: "developer_id"
127 128 129 130 131 132 133 134
    }
    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

135 136 137
  def test_default_scope_on_relations_is_not_cached
    counter = 0
    posts = Class.new(ActiveRecord::Base) {
138 139
      self.table_name = "posts"
      self.inheritance_column = "not_there"
140 141 142
      post = self

      comments = Class.new(ActiveRecord::Base) {
143 144
        self.table_name = "comments"
        self.inheritance_column = "not_there"
145
        belongs_to :post, anonymous_class: post
146 147
        default_scope -> {
          counter += 1
148
          where("id = :inc", inc: counter)
149 150
        }
      }
151
      has_many :comments, anonymous_class: comments, foreign_key: "post_id"
152 153 154 155 156 157 158 159 160
    }
    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

161
  def test_has_many_build_with_options
162 163
    college = College.create(name: "UFMT")
    Student.create(active: true, college_id: college.id, name: "Sarah")
164 165 166 167

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

168
  def test_add_record_to_collection_should_change_its_updated_at
169 170
    ship = Ship.create(name: "dauntless")
    part = ShipPart.create(name: "cockpit")
171 172
    updated_at = part.updated_at

173 174 175
    travel(1.second) do
      ship.parts << part
    end
176 177 178 179 180 181 182 183

    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
184 185
    ship = Ship.create(name: "dauntless")
    part = ShipPart.create(name: "cockpit", ship_id: ship.id)
186 187 188 189

    ship.parts.clear
    part.reload

190
    assert_nil part.ship
191 192 193
    assert !part.updated_at_changed?
  end

194
  def test_create_from_association_should_respect_default_scope
195
    car = Car.create(name: "honda")
196
    assert_equal "honda", car.name
197 198

    bulb = Bulb.create
199
    assert_equal "defaulty", bulb.name
200 201

    bulb = car.bulbs.build
202
    assert_equal "defaulty", bulb.name
203 204

    bulb = car.bulbs.create
205
    assert_equal "defaulty", bulb.name
206 207 208
  end

  def test_build_and_create_from_association_should_respect_passed_attributes_over_default_scope
209
    car = Car.create(name: "honda")
210

211 212
    bulb = car.bulbs.build(name: "exotic")
    assert_equal "exotic", bulb.name
213

214 215
    bulb = car.bulbs.create(name: "exotic")
    assert_equal "exotic", bulb.name
216 217 218 219 220 221

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

    bulb = car.awesome_bulbs.create(frickinawesome: false)
    assert_equal false, bulb.frickinawesome
222 223
  end

224 225 226 227
  def test_build_from_association_should_respect_scope
    author = Author.new

    post = author.thinking_posts.build
228
    assert_equal "So I was thinking", post.title
229 230
  end

231
  def test_create_from_association_with_nil_values_should_work
232
    car = Car.create(name: "honda")
233 234

    bulb = car.bulbs.new(nil)
235
    assert_equal "defaulty", bulb.name
236 237

    bulb = car.bulbs.build(nil)
238
    assert_equal "defaulty", bulb.name
239 240

    bulb = car.bulbs.create(nil)
241
    assert_equal "defaulty", bulb.name
242 243
  end

244
  def test_do_not_call_callbacks_for_delete_all
245
    car = Car.create(name: "honda")
246
    car.funky_bulbs.create!
247
    assert_equal 1, car.funky_bulbs.count
248
    assert_nothing_raised { car.reload.funky_bulbs.delete_all }
249
    assert_equal 0, car.funky_bulbs.count, "bulbs should have been deleted using :delete_all strategy"
250 251
  end

252 253
  def test_delete_all_on_association_is_the_same_as_not_loaded
    author = authors :david
254
    author.thinking_posts.create!(body: "test")
255 256 257
    author.reload
    expected_sql = capture_sql { author.thinking_posts.delete_all }

258
    author.thinking_posts.create!(body: "test")
259 260 261 262 263 264
    author.reload
    author.thinking_posts.inspect
    loaded_sql = capture_sql { author.thinking_posts.delete_all }
    assert_equal(expected_sql, loaded_sql)
  end

265 266
  def test_delete_all_on_association_with_nil_dependency_is_the_same_as_not_loaded
    author = authors :david
267
    author.posts.create!(title: "test", body: "body")
268 269 270
    author.reload
    expected_sql = capture_sql { author.posts.delete_all }

271
    author.posts.create!(title: "test", body: "body")
272 273 274 275 276 277
    author.reload
    author.posts.to_a
    loaded_sql = capture_sql { author.posts.delete_all }
    assert_equal(expected_sql, loaded_sql)
  end

278 279 280
  def test_building_the_associated_object_with_implicit_sti_base_class
    firm = DependentFirm.new
    company = firm.companies.build
281
    assert_kind_of Company, company, "Expected #{company.class} to be a Company"
282 283 284 285
  end

  def test_building_the_associated_object_with_explicit_sti_base_class
    firm = DependentFirm.new
286
    company = firm.companies.build(type: "Company")
287
    assert_kind_of Company, company, "Expected #{company.class} to be a Company"
288 289 290 291
  end

  def test_building_the_associated_object_with_sti_subclass
    firm = DependentFirm.new
292
    company = firm.companies.build(type: "Client")
293
    assert_kind_of Client, company, "Expected #{company.class} to be a Client"
294 295 296 297
  end

  def test_building_the_associated_object_with_an_invalid_type
    firm = DependentFirm.new
298
    assert_raise(ActiveRecord::SubclassNotFound) { firm.companies.build(type: "Invalid") }
299 300 301 302
  end

  def test_building_the_associated_object_with_an_unrelated_type
    firm = DependentFirm.new
303
    assert_raise(ActiveRecord::SubclassNotFound) { firm.companies.build(type: "Account") }
304 305
  end

306 307
  test "building the association with an array" do
    speedometer = Speedometer.new(speedometer_id: "a")
308
    data = [{ name: "first" }, { name: "second" }]
309 310 311 312 313 314 315
    speedometer.minivans.build(data)

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

316
  def test_association_keys_bypass_attribute_protection
317
    car = Car.create(name: "honda")
318 319 320 321

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

322
    bulb = car.bulbs.new car_id: car.id + 1
323 324
    assert_equal car.id, bulb.car_id

325 326 327
    bulb = car.bulbs.build
    assert_equal car.id, bulb.car_id

328
    bulb = car.bulbs.build car_id: car.id + 1
329 330
    assert_equal car.id, bulb.car_id

331 332
    bulb = car.bulbs.create
    assert_equal car.id, bulb.car_id
333

334
    bulb = car.bulbs.create car_id: car.id + 1
335
    assert_equal car.id, bulb.car_id
336 337
  end

338 339 340 341 342 343
  def test_association_protect_foreign_key
    invoice = Invoice.create

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

344
    line_item = invoice.line_items.new invoice_id: invoice.id + 1
345 346 347 348 349
    assert_equal invoice.id, line_item.invoice_id

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

350
    line_item = invoice.line_items.build invoice_id: invoice.id + 1
351 352 353 354 355
    assert_equal invoice.id, line_item.invoice_id

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

356
    line_item = invoice.line_items.create invoice_id: invoice.id + 1
357 358 359
    assert_equal invoice.id, line_item.invoice_id
  end

360 361 362 363
  # 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)
364
    scope = car.foo_bulbs.where_values_hash
365

366
    bulb = car.foo_bulbs.build
367
    assert_not_equal scope, bulb.scope_after_initialize.where_values_hash
368

369
    bulb = car.foo_bulbs.create
370
    assert_not_equal scope, bulb.scope_after_initialize.where_values_hash
371

372
    bulb = car.foo_bulbs.create!
373
    assert_not_equal scope, bulb.scope_after_initialize.where_values_hash
374 375
  end

376
  def test_no_sql_should_be_fired_if_association_already_loaded
377
    Car.create(name: "honda")
378
    bulbs = Car.first.bulbs
B
Brian Cardarella 已提交
379
    bulbs.to_a # to load all instances of bulbs
380

381 382 383
    assert_no_queries do
      bulbs.first()
    end
384

385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
    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

405
    assert_no_queries do
406
      bulbs.third_to_last()
407 408 409
    end

    assert_no_queries do
410
      bulbs.second_to_last()
411 412
    end

413 414 415
    assert_no_queries do
      bulbs.last()
    end
416 417
  end

418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
  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

    assert_not company.clients_of_firm.loaded?
    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

    assert_not company.clients_of_firm.loaded?
    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

458
  def test_create_resets_cached_counters
459
    person = Person.create!(first_name: "tenderlove")
460
    post   = Post.first
461 462

    assert_equal [], person.readers
463
    assert_nil person.readers.find_by_post_id(post.id)
464

465
    person.readers.create(post_id: post.id)
466 467 468 469 470 471 472

    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

473 474
  def test_update_all_respects_association_scope
    person = Person.new
475
    person.first_name = "Naruto"
476 477 478 479 480 481 482 483 484
    person.references << Reference.new
    person.id = 10
    person.references
    person.save!
    assert_equal 1, person.references.update_all(favourite: true)
  end

  def test_exists_respects_association_scope
    person = Person.new
485
    person.first_name = "Sasuke"
486 487 488 489 490 491 492
    person.references << Reference.new
    person.id = 10
    person.references
    person.save!
    assert_predicate person.references, :exists?
  end

493
  # sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first
494
  def test_counting_with_counter_sql
495
    assert_equal 3, Firm.all.merge!(order: "id").first.clients.count
496 497 498
  end

  def test_counting
499
    assert_equal 3, Firm.all.merge!(order: "id").first.plain_clients.count
500 501 502
  end

  def test_counting_with_single_hash
503
    assert_equal 1, Firm.all.merge!(order: "id").first.plain_clients.where(name: "Microsoft").count
504 505 506
  end

  def test_counting_with_column_name_and_hash
507
    assert_equal 3, Firm.all.merge!(order: "id").first.plain_clients.count(:name)
508 509
  end

510 511 512 513 514 515
  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

516
  def test_finding
517
    assert_equal 3, Firm.all.merge!(order: "id").first.clients.length
518 519
  end

520
  def test_finding_array_compatibility
521
    assert_equal 3, Firm.order(:id).find { |f| f.id > 0 }.clients.length
522 523
  end

524 525
  def test_find_many_with_merged_options
    assert_equal 1, companies(:first_firm).limited_clients.size
526
    assert_equal 1, companies(:first_firm).limited_clients.to_a.size
527
    assert_equal 3, companies(:first_firm).limited_clients.limit(nil).to_a.size
528 529
  end

530
  def test_find_should_append_to_association_order
531
    ordered_clients = companies(:first_firm).clients_sorted_desc.order("companies.id")
532
    assert_equal ["id DESC", "companies.id"], ordered_clients.order_values
533 534
  end

535
  def test_dynamic_find_should_respect_association_order
536
    assert_equal companies(:another_first_firm_client), companies(:first_firm).clients_sorted_desc.where("type = 'Client'").first
537
    assert_equal companies(:another_first_firm_client), companies(:first_firm).clients_sorted_desc.find_by_type("Client")
538 539
  end

540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
  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

556 557 558
  def test_taking_with_a_number
    # taking from unloaded Relation
    bob = Author.find(authors(:bob).id)
559 560
    new_post = bob.posts.build
    assert_not bob.posts.loaded?
561 562
    assert_equal [posts(:misc_by_bob)], bob.posts.take(1)
    assert_equal [posts(:misc_by_bob), posts(:other_by_bob)], bob.posts.take(2)
563
    assert_equal [posts(:misc_by_bob), posts(:other_by_bob), new_post], bob.posts.take(3)
564 565

    # taking from loaded Relation
566 567 568 569 570
    bob.posts.load
    assert bob.posts.loaded?
    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)
571 572
  end

573 574 575 576 577 578 579 580 581 582
  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

583 584 585 586 587 588
  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
589
    assert_equal "Summit", Firm.all.merge!(order: "id").first.clients.first.name
590 591 592
  end

  def test_finding_with_different_class_name_and_order
593
    assert_equal "Apex", Firm.all.merge!(order: "id").first.clients_sorted_desc.first.name
594 595 596
  end

  def test_finding_with_foreign_key
597
    assert_equal "Microsoft", Firm.all.merge!(order: "id").first.clients_of_firm.first.name
598 599 600
  end

  def test_finding_with_condition
601
    assert_equal "Microsoft", Firm.all.merge!(order: "id").first.clients_like_ms.first.name
602 603 604
  end

  def test_finding_with_condition_hash
605
    assert_equal "Microsoft", Firm.all.merge!(order: "id").first.clients_like_ms_with_hash_conditions.first.name
606 607
  end

608
  def test_finding_using_primary_key
609
    assert_equal "Summit", Firm.all.merge!(order: "id").first.clients_using_primary_key.first.name
610 611
  end

612
  def test_update_all_on_association_accessed_before_save
613
    firm = Firm.new(name: "Firm")
614 615
    firm.clients << Client.first
    firm.save!
616
    assert_equal firm.clients.count, firm.clients.update_all(description: "Great!")
617 618 619
  end

  def test_update_all_on_association_accessed_before_save_with_explicit_foreign_key
620
    firm = Firm.new(name: "Firm", id: 100)
621 622
    firm.clients << Client.first
    firm.save!
623
    assert_equal firm.clients.count, firm.clients.update_all(description: "Great!")
624 625
  end

626 627
  def test_belongs_to_sanity
    c = Client.new
628
    assert_nil c.firm, "belongs_to failed sanity check on new object"
629 630 631
  end

  def test_find_ids
632
    firm = Firm.all.merge!(order: "id").first
633

634
    assert_raise(ActiveRecord::RecordNotFound) { firm.clients.find }
635 636 637 638 639 640 641 642 643 644 645 646 647

    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

648
    assert_raise(ActiveRecord::RecordNotFound) { firm.clients.find(2, 99) }
649 650
  end

651 652 653 654 655 656 657 658 659 660 661 662
  def test_find_one_message_on_primary_key
    firm = Firm.all.merge!(order: "id").first

    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 已提交
663 664 665
  def test_find_ids_and_inverse_of
    force_signal37_to_load_all_clients_of_firm

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

A
Arthur Neves 已提交
668 669 670 671 672 673 674 675 676
    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

677
  def test_find_all
678
    firm = Firm.all.merge!(order: "id").first
679
    assert_equal 3, firm.clients.where("#{QUOTED_TYPE} = 'Client'").to_a.length
680
    assert_equal 1, firm.clients.where("name = 'Summit'").to_a.length
681 682
  end

683 684 685 686 687
  def test_find_each
    firm = companies(:first_firm)

    assert ! firm.clients.loaded?

688
    assert_queries(4) do
689
      firm.clients.find_each(batch_size: 1) { |c| assert_equal firm.id, c.firm_id }
690 691 692 693 694 695 696 697 698
    end

    assert ! firm.clients.loaded?
  end

  def test_find_each_with_conditions
    firm = companies(:first_firm)

    assert_queries(2) do
699
      firm.clients.where(name: "Microsoft").find_each(batch_size: 1) do |c|
700 701 702 703 704 705 706 707 708 709 710 711 712 713
        assert_equal firm.id, c.firm_id
        assert_equal "Microsoft", c.name
      end
    end

    assert ! firm.clients.loaded?
  end

  def test_find_in_batches
    firm = companies(:first_firm)

    assert ! firm.clients.loaded?

    assert_queries(2) do
714
      firm.clients.find_in_batches(batch_size: 2) do |clients|
715
        clients.each { |c| assert_equal firm.id, c.firm_id }
716 717 718 719 720 721
      end
    end

    assert ! firm.clients.loaded?
  end

722
  def test_find_all_sanitized
723
    # sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first
724
    firm = Firm.all.merge!(order: "id").first
725 726
    summit = firm.clients.where("name = 'Summit'").to_a
    assert_equal summit, firm.clients.where("name = ?", "Summit").to_a
727
    assert_equal summit, firm.clients.where("name = :name", name: "Summit").to_a
728 729 730
  end

  def test_find_first
731
    firm = Firm.all.merge!(order: "id").first
732
    client2 = Client.find(2)
733 734
    assert_equal firm.clients.first, firm.clients.order("id").first
    assert_equal client2, firm.clients.where("#{QUOTED_TYPE} = 'Client'").order("id").first
735 736 737
  end

  def test_find_first_sanitized
738
    firm = Firm.all.merge!(order: "id").first
739
    client2 = Client.find(2)
740 741
    assert_equal client2, firm.clients.merge!(where: ["#{QUOTED_TYPE} = ?", "Client"], order: "id").first
    assert_equal client2, firm.clients.merge!(where: ["#{QUOTED_TYPE} = :type", { type: "Client" }], order: "id").first
742 743
  end

744 745
  def test_find_all_with_include_and_conditions
    assert_nothing_raised do
746
      Developer.all.merge!(joins: :audit_logs, where: { "audit_logs.message" => nil, :name => "Smith" }).to_a
747 748 749
    end
  end

750 751
  def test_find_in_collection
    assert_equal Client.find(2).name, companies(:first_firm).clients.find(2).name
752
    assert_raise(ActiveRecord::RecordNotFound) { companies(:first_firm).clients.find(6) }
753 754 755
  end

  def test_find_grouped
756 757
    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
758
    assert_equal 3, all_clients_of_firm1.size
759 760 761
    assert_equal 1, grouped_clients_of_firm1.size
  end

762
  def test_find_scoped_grouped
763
    assert_equal 1, companies(:first_firm).clients_grouped_by_firm_id.size
764
    assert_equal 1, companies(:first_firm).clients_grouped_by_firm_id.length
765 766
    assert_equal 3, companies(:first_firm).clients_grouped_by_name.size
    assert_equal 3, companies(:first_firm).clients_grouped_by_name.length
767 768
  end

769 770 771 772 773
  def test_find_scoped_grouped_having
    assert_equal 1, authors(:david).popular_grouped_posts.length
    assert_equal 0, authors(:mary).popular_grouped_posts.length
  end

774
  def test_default_select
775
    assert_equal Comment.column_names.sort, posts(:welcome).comments.first.attributes.keys.sort
776 777 778
  end

  def test_select_query_method
779
    assert_equal ["id", "body"], posts(:welcome).comments.select(:id, :body).first.attributes.keys
780 781 782 783
  end

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

786
  def test_select_without_foreign_key
787
    assert_equal companies(:first_firm).accounts.first.credit_limit, companies(:first_firm).accounts.select(:credit_limit).first.credit_limit
788
  end
789

790 791
  def test_adding
    force_signal37_to_load_all_clients_of_firm
792 793 794

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

795 796
    natural = Client.new("name" => "Natural Company")
    companies(:first_firm).clients_of_firm << natural
797
    assert_equal 3, companies(:first_firm).clients_of_firm.size # checking via the collection
798
    assert_equal 3, companies(:first_firm).clients_of_firm.reload.size # checking using the db
799 800 801 802 803 804
    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
805
    first_firm.plain_clients.create(name: "Natural Company")
806 807
    assert_equal 4, first_firm.plain_clients.length
    assert_equal 4, first_firm.plain_clients.size
808 809 810
  end

  def test_create_with_bang_on_has_many_when_parent_is_new_raises
811
    error = assert_raise(ActiveRecord::RecordNotSaved) do
812
      firm = Firm.new
813
      firm.plain_clients.create! name: "Whoever"
814
    end
815 816

    assert_equal "You cannot call create unless the parent is saved", error.message
817 818 819
  end

  def test_regular_create_on_has_many_when_parent_is_new_raises
820
    error = assert_raise(ActiveRecord::RecordNotSaved) do
821
      firm = Firm.new
822
      firm.plain_clients.create name: "Whoever"
823
    end
824 825

    assert_equal "You cannot call create unless the parent is saved", error.message
826 827 828
  end

  def test_create_with_bang_on_has_many_raises_when_record_not_saved
829
    assert_raise(ActiveRecord::RecordInvalid) do
830
      firm = Firm.all.merge!(order: "id").first
831 832 833 834 835
      firm.plain_clients.create!
    end
  end

  def test_create_with_bang_on_habtm_when_parent_is_new_raises
836
    error = assert_raise(ActiveRecord::RecordNotSaved) do
837 838
      Developer.new("name" => "Aredridel").projects.create!
    end
839 840

    assert_equal "You cannot call create unless the parent is saved", error.message
841 842 843
  end

  def test_adding_a_mismatch_class
844 845 846
    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) }
847 848 849 850
  end

  def test_adding_a_collection
    force_signal37_to_load_all_clients_of_firm
851 852 853

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

854
    companies(:first_firm).clients_of_firm.concat([Client.new("name" => "Natural Company"), Client.new("name" => "Apple")])
855
    assert_equal 4, companies(:first_firm).clients_of_firm.size
856
    assert_equal 4, companies(:first_firm).clients_of_firm.reload.size
857 858
  end

859
  def test_transactions_when_adding_to_persisted
860 861
    good = Client.new(name: "Good")
    bad  = Client.new(name: "Bad", raise_on_save: true)
J
Jon Leighton 已提交
862 863 864 865 866 867

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

868
    assert_not_includes companies(:first_firm).clients_of_firm.reload, good
869 870 871
  end

  def test_transactions_when_adding_to_new_record
872
    assert_no_queries(ignore_none: false) do
J
Jon Leighton 已提交
873 874 875
      firm = Firm.new
      firm.clients_of_firm.concat(Client.new("name" => "Natural Company"))
    end
876 877
  end

878 879 880 881 882 883 884
  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

885 886
  def test_new_aliased_to_build
    company = companies(:first_firm)
887
    new_client = assert_no_queries(ignore_none: false) { company.clients_of_firm.new("name" => "Another Client") }
888 889 890 891 892 893 894
    assert !company.clients_of_firm.loaded?

    assert_equal "Another Client", new_client.name
    assert !new_client.persisted?
    assert_equal new_client, company.clients_of_firm.last
  end

895 896
  def test_build
    company = companies(:first_firm)
897
    new_client = assert_no_queries(ignore_none: false) { company.clients_of_firm.build("name" => "Another Client") }
898
    assert !company.clients_of_firm.loaded?
899

900
    assert_equal "Another Client", new_client.name
901
    assert !new_client.persisted?
902 903 904
    assert_equal new_client, company.clients_of_firm.last
  end

905 906 907 908
  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")
909
    assert_equal 4, company.clients_of_firm.size
910
    assert_equal 4, company.clients_of_firm.uniq.size
911 912
  end

913 914 915 916 917 918 919
  def test_collection_not_empty_after_building
    company = companies(:first_firm)
    assert_predicate company.contracts, :empty?
    company.contracts.build
    assert_not_predicate company.contracts, :empty?
  end

920 921 922 923 924 925 926 927 928 929 930 931
  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

932 933
  def test_build_many
    company = companies(:first_firm)
934
    new_clients = assert_no_queries(ignore_none: false) { company.clients_of_firm.build([{ "name" => "Another Client" }, { "name" => "Another Client II" }]) }
935 936 937 938
    assert_equal 2, new_clients.size
  end

  def test_build_followed_by_save_does_not_load_target
939
    companies(:first_firm).clients_of_firm.build("name" => "Another Client")
940 941 942 943 944 945 946 947 948 949 950
    assert companies(:first_firm).save
    assert !companies(:first_firm).clients_of_firm.loaded?
  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
951
      first_topic.replies.build(title: "Not saved", content: "Superstars")
952 953 954 955 956 957
      assert_equal 2, first_topic.replies.size
    end

    assert_equal 2, first_topic.replies.to_ary.size
  end

958 959
  def test_build_via_block
    company = companies(:first_firm)
960
    new_client = assert_no_queries(ignore_none: false) { company.clients_of_firm.build { |client| client.name = "Another Client" } }
961 962 963
    assert !company.clients_of_firm.loaded?

    assert_equal "Another Client", new_client.name
964
    assert !new_client.persisted?
965 966 967 968 969
    assert_equal new_client, company.clients_of_firm.last
  end

  def test_build_many_via_block
    company = companies(:first_firm)
970
    new_clients = assert_no_queries(ignore_none: false) do
971
      company.clients_of_firm.build([{ "name" => "Another Client" }, { "name" => "Another Client II" }]) do |client|
972 973 974 975 976 977 978 979 980
        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

981
  def test_create_without_loading_association
982
    first_firm = companies(:first_firm)
983 984 985
    Firm.column_names
    Client.column_names

986
    assert_equal 2, first_firm.clients_of_firm.size
987 988 989
    first_firm.clients_of_firm.reset

    assert_queries(1) do
990
      first_firm.clients_of_firm.create(name: "Superstars")
991 992
    end

993
    assert_equal 3, first_firm.clients_of_firm.size
994 995 996 997
  end

  def test_create
    force_signal37_to_load_all_clients_of_firm
998 999 1000

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

1001
    new_client = companies(:first_firm).clients_of_firm.create("name" => "Another Client")
1002
    assert new_client.persisted?
1003
    assert_equal new_client, companies(:first_firm).clients_of_firm.last
1004
    assert_equal new_client, companies(:first_firm).clients_of_firm.reload.last
1005 1006 1007
  end

  def test_create_many
1008
    companies(:first_firm).clients_of_firm.create([{ "name" => "Another Client" }, { "name" => "Another Client II" }])
1009
    assert_equal 4, companies(:first_firm).clients_of_firm.reload.size
1010 1011 1012
  end

  def test_create_followed_by_save_does_not_load_target
1013
    companies(:first_firm).clients_of_firm.create("name" => "Another Client")
1014 1015 1016 1017 1018 1019
    assert companies(:first_firm).save
    assert !companies(:first_firm).clients_of_firm.loaded?
  end

  def test_deleting
    force_signal37_to_load_all_clients_of_firm
1020 1021 1022

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

1023
    companies(:first_firm).clients_of_firm.delete(companies(:first_firm).clients_of_firm.first)
1024
    assert_equal 1, companies(:first_firm).clients_of_firm.size
1025
    assert_equal 1, companies(:first_firm).clients_of_firm.reload.size
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
  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

1036 1037 1038
  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.
1039
    ship = Ship.create(name: "Countless", treasures_count: 10)
1040

1041
    assert_not Ship.reflect_on_association(:treasures).has_cached_counter?
1042 1043 1044 1045 1046

    # 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
1047
      ship.treasures.create(name: "Gold")
1048 1049 1050 1051 1052 1053 1054
    end

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

1055
  def test_deleting_updates_counter_cache
J
Jon Leighton 已提交
1056
    topic = Topic.order("id ASC").first
1057 1058 1059 1060 1061 1062 1063
    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

1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
  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

1094 1095 1096 1097 1098 1099 1100 1101 1102
  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

1103
  def test_deleting_updates_counter_cache_without_dependent_option
1104 1105
    post = posts(:welcome)

1106
    assert_difference "post.reload.tags_count", -1 do
1107 1108 1109 1110
      post.taggings.delete(post.taggings.first)
    end
  end

1111 1112
  def test_deleting_updates_counter_cache_with_dependent_delete_all
    post = posts(:welcome)
1113
    post.update_columns(taggings_with_delete_all_count: post.tags_count)
1114 1115 1116 1117 1118 1119

    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

1120 1121
  def test_deleting_updates_counter_cache_with_dependent_destroy
    post = posts(:welcome)
1122
    post.update_columns(taggings_with_destroy_count: post.tags_count)
1123 1124 1125 1126 1127 1128

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

1129 1130 1131 1132 1133 1134 1135
  def test_calling_empty_with_counter_cache
    post = posts(:welcome)
    assert_queries(0) do
      assert_not post.comments.empty?
    end
  end

1136 1137 1138 1139 1140 1141 1142 1143
  def test_custom_named_counter_cache
    topic = topics(:first)

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

1144 1145 1146 1147 1148 1149
  def test_calling_update_attributes_on_id_changes_the_counter_cache
    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
1150
    first_reply.update_attributes(parent_id: nil)
1151 1152
    assert_equal original_count - 1, topic.reload.replies_count

1153
    first_reply.update_attributes(parent_id: topic.id)
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
    assert_equal original_count, topic.reload.replies_count
  end

  def test_calling_update_attributes_changing_ids_doesnt_change_counter_cache
    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

1166
    reply1.update_attributes(parent_id: topic2.id)
1167 1168 1169
    assert_equal original_count1 - 1, topic1.reload.replies_count
    assert_equal original_count2 + 1, topic2.reload.replies_count

1170
    reply2.update_attributes(parent_id: topic1.id)
1171 1172 1173 1174
    assert_equal original_count1, topic1.reload.replies_count
    assert_equal original_count2, topic2.reload.replies_count
  end

1175 1176
  def test_deleting_a_collection
    force_signal37_to_load_all_clients_of_firm
1177 1178 1179

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

1180
    companies(:first_firm).clients_of_firm.create("name" => "Another Client")
1181 1182
    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]])
1183
    assert_equal 0, companies(:first_firm).clients_of_firm.size
1184
    assert_equal 0, companies(:first_firm).clients_of_firm.reload.size
1185 1186 1187 1188
  end

  def test_delete_all
    force_signal37_to_load_all_clients_of_firm
1189 1190 1191

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

1192 1193
    companies(:first_firm).dependent_clients_of_firm.create("name" => "Another Client")
    clients = companies(:first_firm).dependent_clients_of_firm.to_a
1194
    assert_equal 3, clients.count
1195 1196

    assert_difference "Client.count", -(clients.count) do
1197
      companies(:first_firm).dependent_clients_of_firm.delete_all
1198
    end
1199 1200 1201 1202
  end

  def test_delete_all_with_not_yet_loaded_association_collection
    force_signal37_to_load_all_clients_of_firm
1203 1204 1205

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

1206
    companies(:first_firm).clients_of_firm.create("name" => "Another Client")
1207
    assert_equal 3, companies(:first_firm).clients_of_firm.size
1208 1209 1210
    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
1211
    assert_equal 0, companies(:first_firm).clients_of_firm.reload.size
1212 1213
  end

1214
  def test_transaction_when_deleting_persisted
1215 1216
    good = Client.new(name: "Good")
    bad  = Client.new(name: "Bad", raise_on_destroy: true)
J
Jon Leighton 已提交
1217 1218 1219 1220 1221 1222 1223 1224

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

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

1225
    assert_equal [good, bad], companies(:first_firm).clients_of_firm.reload
1226 1227 1228
  end

  def test_transaction_when_deleting_new_record
1229
    assert_no_queries(ignore_none: false) do
J
Jon Leighton 已提交
1230 1231 1232 1233 1234
      firm = Firm.new
      client = Client.new("name" => "New Client")
      firm.clients_of_firm << client
      firm.clients_of_firm.destroy(client)
    end
1235 1236
  end

1237 1238 1239
  def test_clearing_an_association_collection
    firm = companies(:first_firm)
    client_id = firm.clients_of_firm.first.id
1240
    assert_equal 2, firm.clients_of_firm.size
1241

J
Jon Leighton 已提交
1242
    firm.clients_of_firm.clear
1243 1244

    assert_equal 0, firm.clients_of_firm.size
1245
    assert_equal 0, firm.clients_of_firm.reload.size
1246 1247 1248 1249
    assert_equal [], Client.destroyed_client_ids[firm.id]

    # Should not be destroyed since the association is not dependent.
    assert_nothing_raised do
1250
      assert_nil Client.find(client_id).firm
1251 1252 1253
    end
  end

1254 1255 1256
  def test_clearing_updates_counter_cache
    topic = Topic.first

1257
    assert_difference "topic.reload.replies_count", -1 do
1258 1259
      topic.replies.clear
    end
1260 1261
  end

1262 1263 1264 1265
  def test_clearing_updates_counter_cache_when_inverse_counter_cache_is_a_symbol_with_dependent_destroy
    car = Car.first
    car.engines.create!

1266
    assert_difference "car.reload.engines_count", -1 do
1267 1268 1269 1270
      car.engines.clear
    end
  end

1271 1272 1273
  def test_clearing_a_dependent_association_collection
    firm = companies(:first_firm)
    client_id = firm.dependent_clients_of_firm.first.id
1274
    assert_equal 2, firm.dependent_clients_of_firm.size
1275
    assert_equal 1, Client.find_by_id(client_id).client_of
1276

1277
    # :delete_all is called on each client since the dependent options is :destroy
1278 1279 1280
    firm.dependent_clients_of_firm.clear

    assert_equal 0, firm.dependent_clients_of_firm.size
1281
    assert_equal 0, firm.dependent_clients_of_firm.reload.size
1282
    assert_equal [], Client.destroyed_client_ids[firm.id]
1283 1284

    # Should be destroyed since the association is dependent.
1285
    assert_nil Client.find_by_id(client_id)
1286 1287 1288 1289 1290 1291
  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)
1292
    assert_nil Client.find_by_id(client_id)
1293 1294
  end

1295 1296 1297 1298 1299 1300 1301
  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

1302 1303 1304
  def test_clearing_an_exclusively_dependent_association_collection
    firm = companies(:first_firm)
    client_id = firm.exclusively_dependent_clients_of_firm.first.id
1305
    assert_equal 2, firm.exclusively_dependent_clients_of_firm.size
1306 1307 1308 1309 1310 1311 1312 1313

    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
1314
    assert_equal 0, firm.exclusively_dependent_clients_of_firm.reload.size
1315 1316 1317 1318
    # no destroy-filters should have been called
    assert_equal [], Client.destroyed_client_ids[firm.id]

    # Should be destroyed since the association is exclusively dependent.
1319
    assert_nil Client.find_by_id(client_id)
1320 1321 1322 1323
  end

  def test_dependent_association_respects_optional_conditions_on_delete
    firm = companies(:odegy)
1324 1325
    Client.create(client_of: firm.id, name: "BigShot Inc.")
    Client.create(client_of: firm.id, name: "SmallTime Inc.")
1326
    # only one of two clients is included in the association due to the :conditions key
J
Jon Leighton 已提交
1327
    assert_equal 2, Client.where(client_of: firm.id).size
1328 1329 1330
    assert_equal 1, firm.dependent_conditional_clients_of_firm.size
    firm.destroy
    # only the correctly associated client should have been deleted
J
Jon Leighton 已提交
1331
    assert_equal 1, Client.where(client_of: firm.id).size
1332 1333 1334 1335
  end

  def test_dependent_association_respects_optional_sanitized_conditions_on_delete
    firm = companies(:odegy)
1336 1337
    Client.create(client_of: firm.id, name: "BigShot Inc.")
    Client.create(client_of: firm.id, name: "SmallTime Inc.")
1338
    # only one of two clients is included in the association due to the :conditions key
J
Jon Leighton 已提交
1339
    assert_equal 2, Client.where(client_of: firm.id).size
1340 1341 1342
    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 已提交
1343
    assert_equal 1, Client.where(client_of: firm.id).size
1344 1345
  end

1346 1347
  def test_dependent_association_respects_optional_hash_conditions_on_delete
    firm = companies(:odegy)
1348 1349
    Client.create(client_of: firm.id, name: "BigShot Inc.")
    Client.create(client_of: firm.id, name: "SmallTime Inc.")
1350
    # only one of two clients is included in the association due to the :conditions key
J
Jon Leighton 已提交
1351
    assert_equal 2, Client.where(client_of: firm.id).size
1352 1353 1354
    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 已提交
1355
    assert_equal 1, Client.where(client_of: firm.id).size
1356 1357
  end

1358
  def test_delete_all_association_with_primary_key_deletes_correct_records
1359
    firm = Firm.first
1360
    # break the vanilla firm_id foreign key
1361
    assert_equal 3, firm.clients.count
1362
    firm.clients.first.update_columns(firm_id: nil)
1363
    assert_equal 2, firm.clients.reload.count
1364
    assert_equal 2, firm.clients_using_primary_key_with_delete_all.count
1365
    old_record = firm.clients_using_primary_key_with_delete_all.first
1366
    firm = Firm.first
1367
    firm.destroy
1368
    assert_nil Client.find_by_id(old_record.id)
1369
  end
1370

1371 1372
  def test_creation_respects_hash_condition
    ms_client = companies(:first_firm).clients_like_ms_with_hash_conditions.build
1373

1374
    assert        ms_client.save
1375
    assert_equal  "Microsoft", ms_client.name
1376

1377 1378
    another_ms_client = companies(:first_firm).clients_like_ms_with_hash_conditions.create

1379
    assert        another_ms_client.persisted?
1380
    assert_equal  "Microsoft", another_ms_client.name
1381 1382 1383 1384 1385 1386 1387 1388
  end

  def test_clearing_without_initial_access
    firm = companies(:first_firm)

    firm.clients_of_firm.clear

    assert_equal 0, firm.clients_of_firm.size
1389
    assert_equal 0, firm.clients_of_firm.reload.size
1390 1391 1392 1393
  end

  def test_deleting_a_item_which_is_not_in_the_collection
    force_signal37_to_load_all_clients_of_firm
1394 1395 1396

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

1397
    summit = Client.find_by_name("Summit")
1398
    companies(:first_firm).clients_of_firm.delete(summit)
1399
    assert_equal 2, companies(:first_firm).clients_of_firm.size
1400
    assert_equal 2, companies(:first_firm).clients_of_firm.reload.size
1401 1402 1403
    assert_equal 2, summit.client_of
  end

1404
  def test_deleting_by_integer_id
1405
    david = Developer.find(1)
1406

1407
    assert_difference "david.projects.count", -1 do
1408 1409 1410 1411 1412 1413 1414 1415 1416
      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)

1417 1418
    assert_difference "david.projects.count", -1 do
      assert_equal 1, david.projects.delete("1").size
1419 1420 1421
    end

    assert_equal 1, david.projects.size
1422 1423 1424 1425 1426
  end

  def test_deleting_self_type_mismatch
    david = Developer.find(1)
    david.projects.reload
1427
    assert_raise(ActiveRecord::AssociationTypeMismatch) { david.projects.delete(Project.find(1).developers) }
1428 1429
  end

1430 1431 1432
  def test_destroying
    force_signal37_to_load_all_clients_of_firm

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

1435 1436 1437 1438
    assert_difference "Client.count", -1 do
      companies(:first_firm).clients_of_firm.destroy(companies(:first_firm).clients_of_firm.first)
    end

1439
    assert_equal 1, companies(:first_firm).reload.clients_of_firm.size
1440
    assert_equal 1, companies(:first_firm).clients_of_firm.reload.size
1441 1442
  end

1443
  def test_destroying_by_integer_id
1444 1445
    force_signal37_to_load_all_clients_of_firm

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

1448 1449 1450 1451
    assert_difference "Client.count", -1 do
      companies(:first_firm).clients_of_firm.destroy(companies(:first_firm).clients_of_firm.first.id)
    end

1452
    assert_equal 1, companies(:first_firm).reload.clients_of_firm.size
1453
    assert_equal 1, companies(:first_firm).clients_of_firm.reload.size
1454 1455 1456 1457 1458
  end

  def test_destroying_by_string_id
    force_signal37_to_load_all_clients_of_firm

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

1461 1462 1463 1464
    assert_difference "Client.count", -1 do
      companies(:first_firm).clients_of_firm.destroy(companies(:first_firm).clients_of_firm.first.id.to_s)
    end

1465
    assert_equal 1, companies(:first_firm).reload.clients_of_firm.size
1466
    assert_equal 1, companies(:first_firm).clients_of_firm.reload.size
1467 1468
  end

1469 1470
  def test_destroying_a_collection
    force_signal37_to_load_all_clients_of_firm
1471 1472 1473

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

1474
    companies(:first_firm).clients_of_firm.create("name" => "Another Client")
1475
    assert_equal 3, companies(:first_firm).clients_of_firm.size
1476 1477 1478 1479 1480

    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

1481
    assert_equal 1, companies(:first_firm).reload.clients_of_firm.size
1482
    assert_equal 1, companies(:first_firm).clients_of_firm.reload.size
1483 1484
  end

1485 1486
  def test_destroy_all
    force_signal37_to_load_all_clients_of_firm
1487 1488 1489

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

1490 1491 1492 1493
    clients = companies(:first_firm).clients_of_firm.to_a
    assert !clients.empty?, "37signals has clients after load"
    destroyed = companies(:first_firm).clients_of_firm.destroy_all
    assert_equal clients.sort_by(&:id), destroyed.sort_by(&:id)
1494
    assert destroyed.all?(&:frozen?), "destroyed clients should be frozen"
1495
    assert companies(:first_firm).clients_of_firm.empty?, "37signals has no clients after destroy all"
1496
    assert companies(:first_firm).clients_of_firm.reload.empty?, "37signals has no clients after destroy all and refresh"
1497 1498 1499 1500
  end

  def test_dependence
    firm = companies(:first_firm)
1501
    assert_equal 3, firm.clients.size
1502
    firm.destroy
1503
    assert Client.all.merge!(where: "firm_id=#{firm.id}").to_a.empty?
1504 1505
  end

1506 1507
  def test_dependence_for_associations_with_hash_condition
    david = authors(:david)
1508
    assert_difference("Post.count", -1) { assert david.destroy }
1509 1510
  end

1511
  def test_destroy_dependent_when_deleted_from_association
1512
    # sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first
1513
    firm = Firm.all.merge!(order: "id").first
1514
    assert_equal 3, firm.clients.size
1515 1516 1517 1518 1519 1520

    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) }
1521
    assert_equal 2, firm.clients.size
1522 1523 1524 1525 1526
  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"
1527
    reply.replies.create "title" => "neat and simple", "content" => "ain't complaining"
1528 1529 1530 1531 1532 1533 1534

    assert_nothing_raised { topic.destroy }
  end

  def test_dependence_with_transaction_support_on_failure
    firm = companies(:first_firm)
    clients = firm.clients
1535
    assert_equal 3, clients.length
1536
    clients.last.instance_eval { def overwrite_to_raise() raise "Trigger rollback" end }
1537 1538 1539

    firm.destroy rescue "do nothing"

1540
    assert_equal 3, Client.all.merge!(where: "firm_id=#{firm.id}").to_a.size
1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
  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

1563
  def test_restrict_with_exception
1564 1565
    firm = RestrictedWithExceptionFirm.create!(name: "restrict")
    firm.companies.create(name: "child")
1566 1567 1568

    assert !firm.companies.empty?
    assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
1569 1570
    assert RestrictedWithExceptionFirm.exists?(name: "restrict")
    assert firm.companies.exists?(name: "child")
1571 1572 1573
  end

  def test_restrict_with_error
1574 1575
    firm = RestrictedWithErrorFirm.create!(name: "restrict")
    firm.companies.create(name: "child")
1576 1577 1578 1579 1580 1581 1582

    assert !firm.companies.empty?

    firm.destroy

    assert !firm.errors.empty?

1583
    assert_equal "Cannot delete record because dependent companies exist", firm.errors[:base].first
1584 1585
    assert RestrictedWithErrorFirm.exists?(name: "restrict")
    assert firm.companies.exists?(name: "child")
1586 1587
  end

1588 1589
  def test_restrict_with_error_with_locale
    I18n.backend = I18n::Backend::Simple.new
1590
    I18n.backend.store_translations "en", activerecord: { attributes: { restricted_with_error_firm: { companies: "client companies" } } }
1591 1592
    firm = RestrictedWithErrorFirm.create!(name: "restrict")
    firm.companies.create(name: "child")
1593 1594 1595 1596 1597 1598 1599 1600

    assert !firm.companies.empty?

    firm.destroy

    assert !firm.errors.empty?

    assert_equal "Cannot delete record because dependent client companies exist", firm.errors[:base].first
1601 1602
    assert RestrictedWithErrorFirm.exists?(name: "restrict")
    assert firm.companies.exists?(name: "child")
1603 1604 1605 1606
  ensure
    I18n.backend.reload!
  end

1607
  def test_included_in_collection
1608
    assert_equal true, companies(:first_firm).clients.include?(Client.find(2))
1609 1610
  end

1611
  def test_included_in_collection_for_new_records
1612
    client = Client.create(name: "Persisted")
1613
    assert_nil client.client_of
1614
    assert_equal false, Firm.new.clients_of_firm.include?(client),
1615
     "includes a client that does not belong to any firm"
1616 1617
  end

1618
  def test_adding_array_and_collection
J
Jon Leighton 已提交
1619
    assert_nothing_raised { Firm.first.clients + Firm.all.last.clients }
1620 1621 1622
  end

  def test_replace_with_less
1623
    firm = Firm.all.merge!(order: "id").first
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
    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
1637
    firm = Firm.all.merge!(order: "id").first
1638 1639 1640 1641
    firm.clients = [companies(:second_client), Client.new("name" => "New Client")]
    firm.save
    firm.reload
    assert_equal 2, firm.clients.length
1642
    assert_equal false, firm.clients.include?(:first_client)
1643 1644
  end

1645 1646 1647 1648 1649 1650 1651
  def test_replace_failure
    firm = companies(:first_firm)
    account = Account.new
    orig_accounts = firm.accounts.to_a

    assert !account.valid?
    assert !orig_accounts.empty?
1652
    error = assert_raise ActiveRecord::RecordNotSaved do
1653 1654
      firm.accounts = [account]
    end
1655

1656
    assert_equal orig_accounts, firm.accounts
1657 1658
    assert_equal "Failed to replace accounts because one or more of the " \
                 "new records could not be saved.", error.message
1659 1660
  end

1661 1662 1663 1664 1665 1666 1667 1668
  def test_replace_with_same_content
    firm = Firm.first
    firm.clients = []
    firm.save

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

1670
    assert_equal [], firm.send("clients=", [])
1671 1672
  end

1673
  def test_transactions_when_replacing_on_persisted
1674 1675
    good = Client.new(name: "Good")
    bad  = Client.new(name: "Bad", raise_on_save: true)
1676

J
Jon Leighton 已提交
1677 1678 1679 1680 1681 1682 1683
    companies(:first_firm).clients_of_firm = [good]

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

1684
    assert_equal [good], companies(:first_firm).clients_of_firm.reload
1685 1686 1687
  end

  def test_transactions_when_replacing_on_new_record
1688
    assert_no_queries(ignore_none: false) do
J
Jon Leighton 已提交
1689 1690 1691
      firm = Firm.new
      firm.clients_of_firm = [Client.new("name" => "New Client")]
    end
1692 1693
  end

1694
  def test_get_ids
1695
    assert_equal [companies(:first_client).id, companies(:second_client).id, companies(:another_first_firm_client).id], companies(:first_firm).client_ids
1696 1697
  end

1698 1699
  def test_get_ids_for_loaded_associations
    company = companies(:first_firm)
1700
    company.clients.reload
1701 1702 1703 1704 1705 1706 1707 1708 1709
    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)
    assert !company.clients.loaded?
1710
    assert_equal [companies(:first_client).id, companies(:second_client).id, companies(:another_first_firm_client).id], company.client_ids
1711 1712 1713
    assert !company.clients.loaded?
  end

1714 1715 1716 1717 1718
  def test_counter_cache_on_unloaded_association
    car = Car.create(name: "My AppliCar")
    assert_equal car.engines.size, 0
  end

1719 1720 1721 1722
  def test_get_ids_ignores_include_option
    assert_equal [readers(:michael_welcome).id], posts(:welcome).readers_with_person_ids
  end

1723
  def test_get_ids_for_ordered_association
1724
    assert_equal [companies(:another_first_firm_client).id, companies(:second_client).id, companies(:first_client).id], companies(:first_firm).clients_ordered_by_name_ids
1725 1726
  end

1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
  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!
1742
    Contract.create! # another contract
1743
    company = Company.new(name: "Some Company")
1744 1745 1746 1747 1748 1749 1750 1751 1752 1753

    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

1754
  def test_assign_ids_ignoring_blanks
1755
    firm = Firm.create!(name: "Apple")
1756
    firm.client_ids = [companies(:first_client).id, nil, companies(:second_client).id, ""]
1757 1758
    firm.save!

1759
    assert_equal 2, firm.clients.reload.size
1760
    assert_equal true, firm.clients.include?(companies(:second_client))
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770
  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)] },
1771
      lambda { authors(:mary).comments << Comment.create!(body: "Yay", post_id: 424242) },
1772
      lambda { authors(:mary).comments.delete(authors(:mary).comments.first) },
1773
    ].each { |block| assert_raise(ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection, &block) }
1774 1775 1776
  end

  def test_dynamic_find_should_respect_association_order_for_through
1777
    assert_equal Comment.find(10), authors(:david).comments_desc.where("comments.type = 'SpecialComment'").first
1778
    assert_equal Comment.find(10), authors(:david).comments_desc.find_by_type("SpecialComment")
1779 1780 1781 1782 1783 1784 1785 1786 1787
  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 已提交
1788
    firm.clients.load_target
1789

1790 1791 1792 1793
    client = firm.clients.first

    assert_no_queries do
      assert firm.clients.loaded?
1794
      assert_equal true, firm.clients.include?(client)
1795 1796 1797 1798 1799 1800 1801 1802 1803 1804
    end
  end

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

    firm.reload
    assert ! firm.clients.loaded?
    assert_queries(1) do
1805
      assert_equal true, firm.clients.include?(client)
1806 1807 1808 1809 1810 1811
    end
    assert ! firm.clients.loaded?
  end

  def test_include_returns_false_for_non_matching_record_to_verify_scoping
    firm = companies(:first_firm)
1812
    client = Client.create!(name: "Not Associated")
1813 1814

    assert ! firm.clients.loaded?
1815
    assert_equal false, firm.clients.include?(client)
1816 1817
  end

1818
  def test_calling_first_nth_or_last_on_association_should_not_load_association
1819 1820
    firm = companies(:first_firm)
    firm.clients.first
1821
    firm.clients.second
1822 1823 1824 1825 1826 1827
    firm.clients.last
    assert !firm.clients.loaded?
  end

  def test_calling_first_or_last_on_loaded_association_should_not_fetch_with_query
    firm = companies(:first_firm)
J
Jon Leighton 已提交
1828
    firm.clients.load_target
1829 1830
    assert firm.clients.loaded?

1831
    assert_no_queries(ignore_none: false) do
1832 1833 1834 1835 1836 1837 1838 1839 1840
      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)
1841
    firm.clients.build(name: "Foo")
1842 1843 1844 1845
    assert !firm.clients.loaded?

    assert_queries 1 do
      firm.clients.first
1846
      firm.clients.second
1847 1848 1849 1850 1851 1852
      firm.clients.last
    end

    assert firm.clients.loaded?
  end

1853
  def test_calling_first_nth_or_last_on_existing_record_with_create_should_not_load_association
1854
    firm = companies(:first_firm)
1855
    firm.clients.create(name: "Foo")
1856 1857
    assert !firm.clients.loaded?

1858
    assert_queries 3 do
1859
      firm.clients.first
1860
      firm.clients.second
1861 1862 1863 1864 1865 1866
      firm.clients.last
    end

    assert !firm.clients.loaded?
  end

1867
  def test_calling_first_nth_or_last_on_new_record_should_not_run_queries
1868 1869 1870 1871
    firm = Firm.new

    assert_no_queries do
      firm.clients.first
1872
      firm.clients.second
1873 1874 1875
      firm.clients.last
    end
  end
1876

1877
  def test_calling_first_or_last_with_integer_on_association_should_not_load_association
1878
    firm = companies(:first_firm)
1879
    firm.clients.create(name: "Foo")
1880
    assert !firm.clients.loaded?
1881

1882
    assert_queries 2 do
1883 1884 1885 1886
      firm.clients.first(2)
      firm.clients.last(2)
    end

1887
    assert !firm.clients.loaded?
1888 1889
  end

1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925
  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
    assert !firm.clients.loaded?
  end

  def test_calling_many_on_loaded_association_should_not_use_query
    firm = companies(:first_firm)
    firm.clients.collect  # force load
    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
      firm.clients.expects(:size).never
      firm.clients.many? { true }
    end
    assert firm.clients.loaded?
  end

  def test_calling_many_should_return_false_if_none_or_one
    firm = companies(:another_firm)
    assert !firm.clients_like_ms.many?
    assert_equal 0, firm.clients_like_ms.size

    firm = companies(:first_firm)
    assert !firm.limited_clients.many?
    assert_equal 1, firm.limited_clients.size
  end

  def test_calling_many_should_return_true_if_more_than_one
    firm = companies(:first_firm)
    assert firm.clients.many?
1926
    assert_equal 3, firm.clients.size
1927 1928
  end

1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004
  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
    assert !firm.clients.loaded?
  end

  def test_calling_none_on_loaded_association_should_not_use_query
    firm = companies(:first_firm)
    firm.clients.collect  # force load
    assert_no_queries { assert ! firm.clients.none? }
  end

  def test_calling_none_should_defer_to_collection_if_using_a_block
    firm = companies(:first_firm)
    assert_queries(1) do
      firm.clients.expects(:size).never
      firm.clients.none? { true }
    end
    assert firm.clients.loaded?
  end

  def test_calling_none_should_return_true_if_none
    firm = companies(:another_firm)
    assert firm.clients_like_ms.none?
    assert_equal 0, firm.clients_like_ms.size
  end

  def test_calling_none_should_return_false_if_any
    firm = companies(:first_firm)
    assert !firm.limited_clients.none?
    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
    assert !firm.clients.loaded?
  end

  def test_calling_one_on_loaded_association_should_not_use_query
    firm = companies(:first_firm)
    firm.clients.collect  # force load
    assert_no_queries { assert ! firm.clients.one? }
  end

  def test_calling_one_should_defer_to_collection_if_using_a_block
    firm = companies(:first_firm)
    assert_queries(1) do
      firm.clients.expects(:size).never
      firm.clients.one? { true }
    end
    assert firm.clients.loaded?
  end

  def test_calling_one_should_return_false_if_zero
    firm = companies(:another_firm)
    assert ! firm.clients_like_ms.one?
    assert_equal 0, firm.clients_like_ms.size
  end

  def test_calling_one_should_return_true_if_one
    firm = companies(:first_firm)
    assert firm.limited_clients.one?
    assert_equal 1, firm.limited_clients.size
  end

  def test_calling_one_should_return_false_if_more_than_one
    firm = companies(:first_firm)
    assert ! firm.clients.one?
    assert_equal 3, firm.clients.size
  end

2005 2006 2007 2008
  def test_joins_with_namespaced_model_should_use_correct_type
    old = ActiveRecord::Base.store_full_sti_class
    ActiveRecord::Base.store_full_sti_class = true

2009 2010
    firm = Namespaced::Firm.create(name: "Some Company")
    firm.clients.create(name: "Some Client")
2011

2012
    stats = Namespaced::Firm.all.merge!(
2013 2014 2015
      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 已提交
2016
    ).find firm.id
2017 2018 2019 2020 2021
    assert_equal 1, stats.num_clients.to_i
  ensure
    ActiveRecord::Base.store_full_sti_class = old
  end

2022 2023
  def test_association_proxy_transaction_method_starts_transaction_in_association_class
    Comment.expects(:transaction)
2024
    Post.first.comments.transaction do
2025
      # nothing
2026 2027 2028
    end
  end

2029
  def test_sending_new_to_association_proxy_should_have_same_effect_as_calling_new
2030 2031 2032 2033 2034 2035 2036 2037
    client_association = companies(:first_firm).clients
    assert_equal client_association.new.attributes, client_association.send(:new).attributes
  end

  def test_respond_to_private_class_methods
    client_association = companies(:first_firm).clients
    assert !client_association.respond_to?(:private_method)
    assert client_association.respond_to?(:private_method, true)
2038
  end
2039 2040

  def test_creating_using_primary_key
2041 2042
    firm = Firm.all.merge!(order: "id").first
    client = firm.clients_using_primary_key.create!(name: "test")
2043 2044
    assert_equal firm.name, client.firm_name
  end
2045 2046 2047

  def test_defining_has_many_association_with_delete_all_dependency_lazily_evaluates_target_class
    ActiveRecord::Reflection::AssociationReflection.any_instance.expects(:class_name).never
2048
    class_eval(<<-EOF, __FILE__, __LINE__ + 1)
2049 2050 2051 2052 2053 2054 2055 2056
      class DeleteAllModel < ActiveRecord::Base
        has_many :nonentities, :dependent => :delete_all
      end
    EOF
  end

  def test_defining_has_many_association_with_nullify_dependency_lazily_evaluates_target_class
    ActiveRecord::Reflection::AssociationReflection.any_instance.expects(:class_name).never
2057
    class_eval(<<-EOF, __FILE__, __LINE__ + 1)
2058 2059 2060 2061 2062
      class NullifyModel < ActiveRecord::Base
        has_many :nonentities, :dependent => :nullify
      end
    EOF
  end
2063 2064

  def test_attributes_are_being_set_when_initialized_from_has_many_association_with_where_clause
2065
    new_comment = posts(:welcome).comments.where(body: "Some content").build
2066 2067 2068 2069
    assert_equal new_comment.body, "Some content"
  end

  def test_attributes_are_being_set_when_initialized_from_has_many_association_with_multiple_where_clauses
2070
    new_comment = posts(:welcome).comments.where(body: "Some content").where(type: "SpecialComment").build
2071 2072 2073 2074
    assert_equal new_comment.body, "Some content"
    assert_equal new_comment.type, "SpecialComment"
    assert_equal new_comment.post_id, posts(:welcome).id
  end
2075 2076 2077 2078

  def test_include_method_in_has_many_association_should_return_true_for_instance_added_with_build
    post = Post.new
    comment = post.comments.build
2079
    assert_equal true, post.comments.include?(comment)
2080
  end
2081 2082 2083

  def test_load_target_respects_protected_attributes
    topic = Topic.create!
2084
    reply = topic.replies.create(title: "reply 1")
2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101
    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
2102 2103 2104 2105 2106 2107 2108

  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
2109

2110 2111 2112 2113 2114 2115 2116 2117
  def test_dup_should_dup_load_target
    original = topics(:first).replies
    dupped = topics(:first).replies.dup

    assert_not_equal original.object_id, dupped.object_id
    assert_not_equal original.load_target.object_id, dupped.load_target.object_id
  end

2118
  def test_merging_with_custom_attribute_writer
2119
    bulb = Bulb.new(color: "red")
2120 2121 2122 2123 2124 2125 2126
    assert_equal "RED!", bulb.color

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

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

2128
  def test_abstract_class_with_polymorphic_has_many
2129 2130
    post = SubStiPost.create! title: "fooo", body: "baa"
    tagging = Tagging.create! taggable: post
2131 2132
    assert_equal [tagging], post.taggings
  end
F
Farley Knight 已提交
2133

2134
  def test_with_polymorphic_has_many_with_custom_columns_name
2135
    post = Post.create! title: "foo", body: "bar"
2136 2137 2138 2139 2140 2141 2142
    image = Image.create!

    post.images << image

    assert_equal [image], post.images
  end

A
Andy Lindeman 已提交
2143
  def test_build_with_polymorphic_has_many_does_not_allow_to_override_type_and_id
2144
    welcome = posts(:welcome)
2145
    tagging = welcome.taggings.build(taggable_id: 99, taggable_type: "ShouldNotChange")
2146 2147

    assert_equal welcome.id, tagging.taggable_id
2148
    assert_equal "Post", tagging.taggable_type
2149 2150
  end

F
Farley Knight 已提交
2151 2152 2153 2154 2155 2156 2157
  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
2158 2159

  def test_association_attributes_are_available_to_after_initialize
2160
    car = Car.create(name: "honda")
2161 2162
    bulb = car.bulbs.build

2163
    assert_equal car.id, bulb.attributes_after_initialize["car_id"]
2164
  end
2165

2166
  def test_attributes_are_set_when_initialized_from_has_many_null_relationship
2167 2168 2169
    car  = Car.new name: "honda"
    bulb = car.bulbs.where(name: "headlight").first_or_initialize
    assert_equal "headlight", bulb.name
2170 2171 2172
  end

  def test_attributes_are_set_when_initialized_from_polymorphic_has_many_null_relationship
2173 2174
    post    = Post.new title: "title", body: "bar"
    tag     = Tag.create!(name: "foo")
2175 2176 2177 2178

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

    assert_equal tag.id, tagging.tag_id
2179
    assert_equal "Post", tagging.taggable_type
2180 2181
  end

2182
  def test_replace
2183
    car = Car.create(name: "honda")
2184 2185 2186 2187 2188 2189 2190 2191
    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
2192

2193
  def test_replace_returns_target
2194
    car = Car.create(name: "honda")
2195 2196 2197 2198 2199
    bulb1 = car.bulbs.create
    bulb2 = car.bulbs.create
    bulb3 = Bulb.create

    assert_equal [bulb1, bulb2], car.bulbs
2200
    result = car.bulbs.replace([bulb3, bulb1])
2201 2202 2203 2204
    assert_equal [bulb1, bulb3], car.bulbs
    assert_equal [bulb1, bulb3], result
  end

2205 2206 2207 2208
  def test_collection_association_with_private_kernel_method
    firm = companies(:first_firm)
    assert_equal [accounts(:signals37)], firm.accounts.open
  end
J
Jon Leighton 已提交
2209 2210

  test "first_or_initialize adds the record to the association" do
2211
    firm = Firm.create! name: "omg"
J
Jon Leighton 已提交
2212 2213 2214 2215 2216
    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
2217
    firm = Firm.create! name: "omg"
J
Jon Leighton 已提交
2218
    firm.clients_of_firm.load_target
2219
    client = firm.clients_of_firm.first_or_create name: "lol"
J
Jon Leighton 已提交
2220 2221 2222
    assert_equal [client], firm.clients_of_firm
    assert_equal [client], firm.reload.clients_of_firm
  end
2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234

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

    assert post.taggings_with_delete_all.count > 0
    assert !post.taggings_with_delete_all.loaded?

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

2236 2237 2238
  test "has many associations on new records use null relations" do
    post = Post.new

2239
    assert_no_queries(ignore_none: false) do
2240
      assert_equal [], post.comments
2241
      assert_equal [], post.comments.where(body: "omg")
2242
      assert_equal [], post.comments.pluck(:body)
2243
      assert_equal 0,  post.comments.sum(:id)
V
Vipul A M 已提交
2244
      assert_equal 0,  post.comments.count
2245 2246
    end
  end
2247 2248 2249 2250 2251

  test "collection proxy respects default scope" do
    author = authors(:mary)
    assert !author.first_posts.exists?
  end
J
Jon Leighton 已提交
2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263

  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
    assert_equal "hello", post.comments_with_extend_2.greeting
  end
2264 2265 2266 2267 2268

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

    post = david.posts.first
2269
    post.type = "PostWithSpecialCategorization"
2270 2271 2272 2273 2274 2275 2276 2277 2278 2279
    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
2280 2281

  test "does not duplicate associations when used with natural primary keys" do
2282
    speedometer = Speedometer.create!(id: "4")
2283
    speedometer.minivans.create!(minivan_id: "a-van-red" , name: "a van", color: "red")
2284 2285 2286 2287

    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 已提交
2288 2289 2290 2291 2292 2293 2294 2295 2296

  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
2297

2298
  test "can unscope and where the default scope of the associated model" do
2299
    Car.has_many :other_bulbs, -> { unscope(where: [:name]).where(name: "other") }, class_name: "Bulb"
2300 2301 2302 2303 2304 2305 2306 2307 2308
    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
2309
    Car.has_many :old_bulbs, -> { rewhere(name: "old") }, class_name: "Bulb"
2310 2311 2312 2313 2314 2315 2316 2317
    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

2318
  test "unscopes the default scope of associated model when used with include" do
2319 2320 2321 2322 2323 2324 2325
    car = Car.create!
    bulb = Bulb.create! name: "other", car: car

    assert_equal bulb, Car.find(car.id).all_bulbs.first
    assert_equal bulb, Car.includes(:all_bulbs).find(car.id).all_bulbs.first
  end

2326 2327 2328 2329
  test "raises RecordNotDestroyed when replaced child can't be destroyed" do
    car = Car.create!
    original_child = FailedBulb.create!(car: car)

2330
    error = assert_raise(ActiveRecord::RecordNotDestroyed) do
2331 2332 2333 2334
      car.failed_bulbs = [FailedBulb.create!]
    end

    assert_equal [original_child], car.reload.failed_bulbs
2335
    assert_equal "Failed to destroy the record", error.message
2336
  end
2337

2338
  test "updates counter cache when default scope is given" do
2339 2340 2341 2342 2343
    topic = DefaultRejectedTopic.create approved: true

    assert_difference "topic.reload.replies_count", 1 do
      topic.approved_replies.create!
    end
2344
  end
2345

2346 2347
  test "dangerous association name raises ArgumentError" do
    [:errors, "errors", :save, "save"].each do |name|
2348 2349 2350 2351 2352 2353 2354
      assert_raises(ArgumentError, "Association #{name} should not be allowed") do
        Class.new(ActiveRecord::Base) do
          has_many name
        end
      end
    end
  end
2355

2356
  test "passes custom context validation to validate children" do
2357 2358
    pirate = FamousPirate.new
    pirate.famous_ships << ship = FamousShip.new
2359 2360 2361

    assert pirate.valid?
    assert_not pirate.valid?(:conference)
2362 2363
    assert_equal "can't be blank", ship.errors[:name].first
  end
2364

2365
  test "association with instance dependent scope" do
2366 2367 2368 2369 2370 2371 2372 2373
    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
2374

2375
  test "associations autosaves when object is already persisted" do
2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386
    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
2387

2388
  test "associations replace in memory when records have the same id" do
2389 2390 2391 2392 2393 2394 2395 2396 2397 2398
    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

2399
  test "in memory replacement executes no queries" do
2400 2401 2402 2403 2404 2405 2406 2407 2408 2409
    bulb = Bulb.create!
    car = Car.create!(bulbs: [bulb])

    new_bulb = Bulb.find(bulb.id)

    assert_no_queries do
      car.bulbs = [new_bulb]
    end
  end

2410
  test "in memory replacements do not execute callbacks" do
2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430
    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

2431
  test "in memory replacements sets inverse instance" do
2432 2433 2434 2435 2436 2437 2438 2439 2440
    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

2441
  test "in memory replacement maintains order" do
2442 2443 2444 2445 2446 2447 2448 2449 2450
    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
2451

2452
  test "double insertion of new object to association when same association used in the after create callback of a new object" do
2453
    reset_callbacks(:save, Bulb) do
2454
      Bulb.after_save { |record| record.car.bulbs.load }
2455 2456 2457 2458
      car = Car.create!
      car.bulbs << Bulb.new
      assert_equal 1, car.bulbs.size
    end
2459 2460
  end

2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489
  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
2490 2491

  def test_ids_reader_memoization
2492
    car = Car.create!(name: "Tofaş")
2493 2494 2495 2496 2497
    bulb = Bulb.create!(car: car)

    assert_equal [bulb.id], car.bulb_ids
    assert_no_queries { car.bulb_ids }
  end
2498

2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509
  def test_loading_association_in_validate_callback_doesnt_affect_persistence
    reset_callbacks(:validation, Bulb) do
      Bulb.after_validation { |m| m.car.bulbs.load }

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

      assert_equal [bulb], car.bulbs
    end
  end

2510 2511 2512 2513 2514
  private

    def force_signal37_to_load_all_clients_of_firm
      companies(:first_firm).clients_of_firm.load_target
    end
2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528

    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
2529
end