has_many_associations_test.rb 76.5 KB
Newer Older
1
require "cases/helper"
2
require 'models/developer'
A
Arun Agrawal 已提交
3
require 'models/computer'
4 5
require 'models/project'
require 'models/company'
F
Farley Knight 已提交
6
require 'models/contract'
7 8 9
require 'models/topic'
require 'models/reply'
require 'models/category'
10
require 'models/image'
11 12
require 'models/post'
require 'models/author'
13
require 'models/essay'
14 15 16
require 'models/comment'
require 'models/person'
require 'models/reader'
J
Jeremy Kemper 已提交
17
require 'models/tagging'
18
require 'models/tag'
19 20
require 'models/invoice'
require 'models/line_item'
21 22
require 'models/car'
require 'models/bulb'
23
require 'models/engine'
24
require 'models/categorization'
25 26
require 'models/minivan'
require 'models/speedometer'
27 28
require 'models/reference'
require 'models/job'
29 30
require 'models/college'
require 'models/student'
31 32
require 'models/pirate'
require 'models/ship'
33
require 'models/ship_part'
34 35
require 'models/treasure'
require 'models/parrot'
36
require 'models/tyre'
37 38
require 'models/subscriber'
require 'models/subscription'
39 40
require 'models/zine'
require 'models/interest'
41

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

  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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
class HasManyAssociationsTestPrimaryKeys < ActiveRecord::TestCase
  fixtures :authors, :essays, :subscribers, :subscriptions, :people

  def test_custom_primary_key_on_new_record_should_fetch_with_query
    subscriber = Subscriber.new(nick: 'webster132')
    assert !subscriber.subscriptions.loaded?

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

    assert_equal subscriber.subscriptions, Subscription.where(subscriber_id: 'webster132')
  end

  def test_association_primary_key_on_new_record_should_fetch_with_query
    author = Author.new(:name => "David")
    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)
    david.essays = [Essay.create!(name: "Remote Work" )]
    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 119 120 121 122 123
  def test_anonymous_has_many
    developer = Class.new(ActiveRecord::Base) {
      self.table_name = 'developers'
      dev = self

      developer_project = Class.new(ActiveRecord::Base) {
        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 138 139 140 141 142 143 144
  def test_default_scope_on_relations_is_not_cached
    counter = 0
    posts = Class.new(ActiveRecord::Base) {
      self.table_name = 'posts'
      self.inheritance_column = 'not_there'
      post = self

      comments = Class.new(ActiveRecord::Base) {
        self.table_name = 'comments'
        self.inheritance_column = 'not_there'
145
        belongs_to :post, :anonymous_class => post
146 147 148 149 150
        default_scope -> {
          counter += 1
          where("id = :inc", :inc => counter)
        }
      }
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 162
  def test_has_many_build_with_options
    college = College.create(name: 'UFMT')
163
    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 169 170 171 172
  def test_add_record_to_collection_should_change_its_updated_at
    ship = Ship.create(name: 'dauntless')
    part = ShipPart.create(name: 'cockpit')
    updated_at = part.updated_at

173 174 175
    travel(1.second) do
      ship.parts << part
    end
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193

    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
    ship = Ship.create(name: 'dauntless')
    part = ShipPart.create(name: 'cockpit', ship_id: ship.id)

    ship.parts.clear
    part.reload

    assert_equal nil, part.ship
    assert !part.updated_at_changed?
  end

194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
  def test_create_from_association_should_respect_default_scope
    car = Car.create(:name => 'honda')
    assert_equal 'honda', car.name

    bulb = Bulb.create
    assert_equal 'defaulty', bulb.name

    bulb = car.bulbs.build
    assert_equal 'defaulty', bulb.name

    bulb = car.bulbs.create
    assert_equal 'defaulty', bulb.name

    bulb = car.bulbs.create(:name => 'exotic')
    assert_equal 'exotic', bulb.name
  end

211 212 213 214 215 216 217
  def test_build_from_association_should_respect_scope
    author = Author.new

    post = author.thinking_posts.build
    assert_equal 'So I was thinking', post.title
  end

218 219 220 221 222 223 224 225 226 227 228 229 230
  def test_create_from_association_with_nil_values_should_work
    car = Car.create(:name => 'honda')

    bulb = car.bulbs.new(nil)
    assert_equal 'defaulty', bulb.name

    bulb = car.bulbs.build(nil)
    assert_equal 'defaulty', bulb.name

    bulb = car.bulbs.create(nil)
    assert_equal 'defaulty', bulb.name
  end

231 232 233 234
  def test_do_not_call_callbacks_for_delete_all
    car = Car.create(:name => 'honda')
    car.funky_bulbs.create!
    assert_nothing_raised { car.reload.funky_bulbs.delete_all }
V
Vipul A M 已提交
235
    assert_equal 0, Bulb.count, "bulbs should have been deleted using :delete_all strategy"
236 237
  end

238 239 240 241 242 243 244 245 246 247 248 249 250
  def test_delete_all_on_association_is_the_same_as_not_loaded
    author = authors :david
    author.thinking_posts.create!(:body => "test")
    author.reload
    expected_sql = capture_sql { author.thinking_posts.delete_all }

    author.thinking_posts.create!(:body => "test")
    author.reload
    author.thinking_posts.inspect
    loaded_sql = capture_sql { author.thinking_posts.delete_all }
    assert_equal(expected_sql, loaded_sql)
  end

251 252 253 254 255 256 257 258 259 260 261 262 263
  def test_delete_all_on_association_with_nil_dependency_is_the_same_as_not_loaded
    author = authors :david
    author.posts.create!(:title => "test", :body => "body")
    author.reload
    expected_sql = capture_sql { author.posts.delete_all }

    author.posts.create!(:title => "test", :body => "body")
    author.reload
    author.posts.to_a
    loaded_sql = capture_sql { author.posts.delete_all }
    assert_equal(expected_sql, loaded_sql)
  end

264 265 266
  def test_building_the_associated_object_with_implicit_sti_base_class
    firm = DependentFirm.new
    company = firm.companies.build
267
    assert_kind_of Company, company, "Expected #{company.class} to be a Company"
268 269 270 271 272
  end

  def test_building_the_associated_object_with_explicit_sti_base_class
    firm = DependentFirm.new
    company = firm.companies.build(:type => "Company")
273
    assert_kind_of Company, company, "Expected #{company.class} to be a Company"
274 275 276 277 278
  end

  def test_building_the_associated_object_with_sti_subclass
    firm = DependentFirm.new
    company = firm.companies.build(:type => "Client")
279
    assert_kind_of Client, company, "Expected #{company.class} to be a Client"
280 281 282 283 284 285 286 287 288 289 290 291
  end

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

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

292 293 294 295 296 297 298 299 300 301
  test "building the association with an array" do
    speedometer = Speedometer.new(speedometer_id: "a")
    data = [{name: "first"}, {name: "second"}]
    speedometer.minivans.build(data)

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

302
  def test_association_keys_bypass_attribute_protection
303 304 305 306 307
    car = Car.create(:name => 'honda')

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

308 309 310
    bulb = car.bulbs.new :car_id => car.id + 1
    assert_equal car.id, bulb.car_id

311 312 313
    bulb = car.bulbs.build
    assert_equal car.id, bulb.car_id

314 315 316
    bulb = car.bulbs.build :car_id => car.id + 1
    assert_equal car.id, bulb.car_id

317 318
    bulb = car.bulbs.create
    assert_equal car.id, bulb.car_id
319 320 321

    bulb = car.bulbs.create :car_id => car.id + 1
    assert_equal car.id, bulb.car_id
322 323
  end

324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
  def test_association_protect_foreign_key
    invoice = Invoice.create

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

    line_item = invoice.line_items.new :invoice_id => invoice.id + 1
    assert_equal invoice.id, line_item.invoice_id

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

    line_item = invoice.line_items.build :invoice_id => invoice.id + 1
    assert_equal invoice.id, line_item.invoice_id

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

    line_item = invoice.line_items.create :invoice_id => invoice.id + 1
    assert_equal invoice.id, line_item.invoice_id
  end

346 347 348 349
  # 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)
350
    scope = car.foo_bulbs.where_values_hash
351

352
    bulb = car.foo_bulbs.build
353
    assert_not_equal scope, bulb.scope_after_initialize.where_values_hash
354

355
    bulb = car.foo_bulbs.create
356
    assert_not_equal scope, bulb.scope_after_initialize.where_values_hash
357

358
    bulb = car.foo_bulbs.create!
359
    assert_not_equal scope, bulb.scope_after_initialize.where_values_hash
360 361
  end

362
  def test_no_sql_should_be_fired_if_association_already_loaded
A
Aaron Patterson 已提交
363
    Car.create(:name => 'honda')
364
    bulbs = Car.first.bulbs
B
Brian Cardarella 已提交
365
    bulbs.to_a # to load all instances of bulbs
366

367 368 369 370
    assert_no_queries do
      bulbs.first()
      bulbs.first({})
    end
371

372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
    assert_no_queries do
      bulbs.second()
      bulbs.second({})
    end

    assert_no_queries do
      bulbs.third()
      bulbs.third({})
    end

    assert_no_queries do
      bulbs.fourth()
      bulbs.fourth({})
    end

    assert_no_queries do
      bulbs.fifth()
      bulbs.fifth({})
    end

    assert_no_queries do
      bulbs.forty_two()
      bulbs.forty_two({})
    end

397 398 399 400
    assert_no_queries do
      bulbs.last()
      bulbs.last({})
    end
401 402
  end

403 404 405
  def test_create_resets_cached_counters
    person = Person.create!(:first_name => 'tenderlove')
    post   = Post.first
406 407

    assert_equal [], person.readers
408
    assert_nil person.readers.find_by_post_id(post.id)
409

410
    person.readers.create(:post_id => post.id)
411 412 413 414 415 416 417

    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

418 419 420 421
  def force_signal37_to_load_all_clients_of_firm
    companies(:first_firm).clients_of_firm.each {|f| }
  end

422
  # sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first
423
  def test_counting_with_counter_sql
424
    assert_equal 3, Firm.all.merge!(:order => "id").first.clients.count
425 426 427
  end

  def test_counting
428
    assert_equal 3, Firm.all.merge!(:order => "id").first.plain_clients.count
429 430 431
  end

  def test_counting_with_single_hash
432
    assert_equal 1, Firm.all.merge!(:order => "id").first.plain_clients.where(:name => "Microsoft").count
433 434 435
  end

  def test_counting_with_column_name_and_hash
436
    assert_equal 3, Firm.all.merge!(:order => "id").first.plain_clients.count(:name)
437 438
  end

439 440 441 442 443 444
  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

445
  def test_finding
446
    assert_equal 3, Firm.all.merge!(:order => "id").first.clients.length
447 448
  end

449
  def test_finding_array_compatibility
450
    assert_equal 3, Firm.order(:id).find{|f| f.id > 0}.clients.length
451 452
  end

453 454
  def test_find_many_with_merged_options
    assert_equal 1, companies(:first_firm).limited_clients.size
455
    assert_equal 1, companies(:first_firm).limited_clients.to_a.size
456
    assert_equal 3, companies(:first_firm).limited_clients.limit(nil).to_a.size
457 458
  end

459
  def test_find_should_append_to_association_order
460
    ordered_clients =  companies(:first_firm).clients_sorted_desc.order('companies.id')
461
    assert_equal ['id DESC', 'companies.id'], ordered_clients.order_values
462 463
  end

464
  def test_dynamic_find_should_respect_association_order
465 466
    assert_equal companies(:another_first_firm_client), companies(:first_firm).clients_sorted_desc.where("type = 'Client'").first
    assert_equal companies(:another_first_firm_client), companies(:first_firm).clients_sorted_desc.find_by_type('Client')
467 468
  end

469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
  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

485 486 487 488 489 490 491 492 493 494 495 496 497
  def test_taking_with_a_number
    # taking from unloaded Relation
    bob = Author.find(authors(:bob).id)
    assert_equal [posts(:misc_by_bob)], bob.posts.take(1)
    bob = Author.find(authors(:bob).id)
    assert_equal [posts(:misc_by_bob), posts(:other_by_bob)], bob.posts.take(2)

    # taking from loaded Relation
    bob.posts.to_a
    assert_equal [posts(:misc_by_bob)], authors(:bob).posts.take(1)
    assert_equal [posts(:misc_by_bob), posts(:other_by_bob)], authors(:bob).posts.take(2)
  end

498 499 500 501 502 503 504 505 506 507
  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

508 509 510 511 512 513
  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
514
    assert_equal "Summit", Firm.all.merge!(:order => "id").first.clients.first.name
515 516 517
  end

  def test_finding_with_different_class_name_and_order
518
    assert_equal "Apex", Firm.all.merge!(:order => "id").first.clients_sorted_desc.first.name
519 520 521
  end

  def test_finding_with_foreign_key
522
    assert_equal "Microsoft", Firm.all.merge!(:order => "id").first.clients_of_firm.first.name
523 524 525
  end

  def test_finding_with_condition
526
    assert_equal "Microsoft", Firm.all.merge!(:order => "id").first.clients_like_ms.first.name
527 528 529
  end

  def test_finding_with_condition_hash
530
    assert_equal "Microsoft", Firm.all.merge!(:order => "id").first.clients_like_ms_with_hash_conditions.first.name
531 532
  end

533
  def test_finding_using_primary_key
534
    assert_equal "Summit", Firm.all.merge!(:order => "id").first.clients_using_primary_key.first.name
535 536
  end

537 538
  def test_update_all_on_association_accessed_before_save
    firm = Firm.new(name: 'Firm')
539
    clients_proxy_id = firm.clients.object_id
540 541 542
    firm.clients << Client.first
    firm.save!
    assert_equal firm.clients.count, firm.clients.update_all(description: 'Great!')
543 544 545 546 547 548 549 550 551 552 553
    assert_not_equal clients_proxy_id, firm.clients.object_id
  end

  def test_update_all_on_association_accessed_before_save_with_explicit_foreign_key
    # We can use the same cached proxy object because the id is available for the scope
    firm = Firm.new(name: 'Firm', id: 100)
    clients_proxy_id = firm.clients.object_id
    firm.clients << Client.first
    firm.save!
    assert_equal firm.clients.count, firm.clients.update_all(description: 'Great!')
    assert_equal clients_proxy_id, firm.clients.object_id
554 555
  end

556 557
  def test_belongs_to_sanity
    c = Client.new
558
    assert_nil c.firm, "belongs_to failed sanity check on new object"
559 560 561
  end

  def test_find_ids
562
    firm = Firm.all.merge!(:order => "id").first
563

564
    assert_raise(ActiveRecord::RecordNotFound) { firm.clients.find }
565 566 567 568 569 570 571 572 573 574 575 576 577

    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

578
    assert_raise(ActiveRecord::RecordNotFound) { firm.clients.find(2, 99) }
579 580
  end

A
Arthur Neves 已提交
581 582 583 584 585 586 587 588 589 590 591 592
  def test_find_ids_and_inverse_of
    force_signal37_to_load_all_clients_of_firm

    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

593
  def test_find_all
594
    firm = Firm.all.merge!(:order => "id").first
595
    assert_equal 3, firm.clients.where("#{QUOTED_TYPE} = 'Client'").to_a.length
596
    assert_equal 1, firm.clients.where("name = 'Summit'").to_a.length
597 598
  end

599 600 601 602 603
  def test_find_each
    firm = companies(:first_firm)

    assert ! firm.clients.loaded?

604
    assert_queries(4) do
605 606 607 608 609 610 611 612 613 614
      firm.clients.find_each(:batch_size => 1) {|c| assert_equal firm.id, c.firm_id }
    end

    assert ! firm.clients.loaded?
  end

  def test_find_each_with_conditions
    firm = companies(:first_firm)

    assert_queries(2) do
615
      firm.clients.where(name: 'Microsoft').find_each(batch_size: 1) do |c|
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
        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
      firm.clients.find_in_batches(:batch_size => 2) do |clients|
        clients.each {|c| assert_equal firm.id, c.firm_id }
      end
    end

    assert ! firm.clients.loaded?
  end

638
  def test_find_all_sanitized
639
    # sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first
640 641 642 643
    firm = Firm.all.merge!(:order => "id").first
    summit = firm.clients.where("name = 'Summit'").to_a
    assert_equal summit, firm.clients.where("name = ?", "Summit").to_a
    assert_equal summit, firm.clients.where("name = :name", { :name => "Summit" }).to_a
644 645 646
  end

  def test_find_first
647
    firm = Firm.all.merge!(:order => "id").first
648
    client2 = Client.find(2)
649 650
    assert_equal firm.clients.first, firm.clients.order("id").first
    assert_equal client2, firm.clients.where("#{QUOTED_TYPE} = 'Client'").order("id").first
651 652 653
  end

  def test_find_first_sanitized
654
    firm = Firm.all.merge!(:order => "id").first
655
    client2 = Client.find(2)
656 657
    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
658 659
  end

660 661
  def test_find_all_with_include_and_conditions
    assert_nothing_raised do
662
      Developer.all.merge!(:joins => :audit_logs, :where => {'audit_logs.message' => nil, :name => 'Smith'}).to_a
663 664 665
    end
  end

666 667
  def test_find_in_collection
    assert_equal Client.find(2).name, companies(:first_firm).clients.find(2).name
668
    assert_raise(ActiveRecord::RecordNotFound) { companies(:first_firm).clients.find(6) }
669 670 671
  end

  def test_find_grouped
672 673
    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
674
    assert_equal 3, all_clients_of_firm1.size
675 676 677
    assert_equal 1, grouped_clients_of_firm1.size
  end

678
  def test_find_scoped_grouped
679
    assert_equal 1, companies(:first_firm).clients_grouped_by_firm_id.size
680
    assert_equal 1, companies(:first_firm).clients_grouped_by_firm_id.length
681 682
    assert_equal 3, companies(:first_firm).clients_grouped_by_name.size
    assert_equal 3, companies(:first_firm).clients_grouped_by_name.length
683 684
  end

685 686 687 688 689
  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

690
  def test_default_select
691
    assert_equal Comment.column_names.sort, posts(:welcome).comments.first.attributes.keys.sort
692 693 694
  end

  def test_select_query_method
695 696 697 698 699
    assert_equal ['id', 'body'], posts(:welcome).comments.select(:id, :body).first.attributes.keys
  end

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

702
  def test_select_without_foreign_key
703
    assert_equal companies(:first_firm).accounts.first.credit_limit, companies(:first_firm).accounts.select(:credit_limit).first.credit_limit
704
  end
705

706 707 708 709
  def test_adding
    force_signal37_to_load_all_clients_of_firm
    natural = Client.new("name" => "Natural Company")
    companies(:first_firm).clients_of_firm << natural
710
    assert_equal 3, companies(:first_firm).clients_of_firm.size # checking via the collection
711
    assert_equal 3, companies(:first_firm).clients_of_firm.reload.size # checking using the db
712 713 714 715 716 717
    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
718 719 720
    first_firm.plain_clients.create(:name => "Natural Company")
    assert_equal 4, first_firm.plain_clients.length
    assert_equal 4, first_firm.plain_clients.size
721 722 723
  end

  def test_create_with_bang_on_has_many_when_parent_is_new_raises
724
    error = assert_raise(ActiveRecord::RecordNotSaved) do
725 726 727
      firm = Firm.new
      firm.plain_clients.create! :name=>"Whoever"
    end
728 729

    assert_equal "You cannot call create unless the parent is saved", error.message
730 731 732
  end

  def test_regular_create_on_has_many_when_parent_is_new_raises
733
    error = assert_raise(ActiveRecord::RecordNotSaved) do
734 735 736
      firm = Firm.new
      firm.plain_clients.create :name=>"Whoever"
    end
737 738

    assert_equal "You cannot call create unless the parent is saved", error.message
739 740 741
  end

  def test_create_with_bang_on_has_many_raises_when_record_not_saved
742
    assert_raise(ActiveRecord::RecordInvalid) do
743
      firm = Firm.all.merge!(:order => "id").first
744 745 746 747 748
      firm.plain_clients.create!
    end
  end

  def test_create_with_bang_on_habtm_when_parent_is_new_raises
749
    error = assert_raise(ActiveRecord::RecordNotSaved) do
750 751
      Developer.new("name" => "Aredridel").projects.create!
    end
752 753

    assert_equal "You cannot call create unless the parent is saved", error.message
754 755 756
  end

  def test_adding_a_mismatch_class
757 758 759
    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) }
760 761 762 763 764
  end

  def test_adding_a_collection
    force_signal37_to_load_all_clients_of_firm
    companies(:first_firm).clients_of_firm.concat([Client.new("name" => "Natural Company"), Client.new("name" => "Apple")])
765
    assert_equal 4, companies(:first_firm).clients_of_firm.size
766
    assert_equal 4, companies(:first_firm).clients_of_firm.reload.size
767 768
  end

769
  def test_transactions_when_adding_to_persisted
J
Jon Leighton 已提交
770 771 772 773 774 775 776 777
    good = Client.new(:name => "Good")
    bad  = Client.new(:name => "Bad", :raise_on_save => true)

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

778
    assert !companies(:first_firm).clients_of_firm.reload.include?(good)
779 780 781
  end

  def test_transactions_when_adding_to_new_record
782
    assert_no_queries(ignore_none: false) do
J
Jon Leighton 已提交
783 784 785
      firm = Firm.new
      firm.clients_of_firm.concat(Client.new("name" => "Natural Company"))
    end
786 787
  end

788 789 790 791 792 793 794
  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

795 796
  def test_new_aliased_to_build
    company = companies(:first_firm)
797
    new_client = assert_no_queries(ignore_none: false) { company.clients_of_firm.new("name" => "Another Client") }
798 799 800 801 802 803 804
    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

805 806
  def test_build
    company = companies(:first_firm)
807
    new_client = assert_no_queries(ignore_none: false) { company.clients_of_firm.build("name" => "Another Client") }
808
    assert !company.clients_of_firm.loaded?
809

810
    assert_equal "Another Client", new_client.name
811
    assert !new_client.persisted?
812 813 814
    assert_equal new_client, company.clients_of_firm.last
  end

815 816 817 818
  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")
819
    assert_equal 4, company.clients_of_firm.size
820 821
  end

822 823 824 825 826 827 828
  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

829 830 831 832 833 834 835 836 837 838 839 840
  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

841 842
  def test_build_many
    company = companies(:first_firm)
843
    new_clients = assert_no_queries(ignore_none: false) { company.clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}]) }
844 845 846 847
    assert_equal 2, new_clients.size
  end

  def test_build_followed_by_save_does_not_load_target
848
    companies(:first_firm).clients_of_firm.build("name" => "Another Client")
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
    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
      first_topic.replies.build(:title => "Not saved", :content => "Superstars")
      assert_equal 2, first_topic.replies.size
    end

    assert_equal 2, first_topic.replies.to_ary.size
  end

867 868
  def test_build_via_block
    company = companies(:first_firm)
869
    new_client = assert_no_queries(ignore_none: false) { company.clients_of_firm.build {|client| client.name = "Another Client" } }
870 871 872
    assert !company.clients_of_firm.loaded?

    assert_equal "Another Client", new_client.name
873
    assert !new_client.persisted?
874 875 876 877 878
    assert_equal new_client, company.clients_of_firm.last
  end

  def test_build_many_via_block
    company = companies(:first_firm)
879
    new_clients = assert_no_queries(ignore_none: false) do
880 881 882 883 884 885 886 887 888 889
      company.clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}]) do |client|
        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

890 891 892 893 894
  def test_create_without_loading_association
    first_firm  = companies(:first_firm)
    Firm.column_names
    Client.column_names

895
    assert_equal 2, first_firm.clients_of_firm.size
896 897 898 899 900 901
    first_firm.clients_of_firm.reset

    assert_queries(1) do
      first_firm.clients_of_firm.create(:name => "Superstars")
    end

902
    assert_equal 3, first_firm.clients_of_firm.size
903 904 905 906 907
  end

  def test_create
    force_signal37_to_load_all_clients_of_firm
    new_client = companies(:first_firm).clients_of_firm.create("name" => "Another Client")
908
    assert new_client.persisted?
909
    assert_equal new_client, companies(:first_firm).clients_of_firm.last
910
    assert_equal new_client, companies(:first_firm).clients_of_firm.reload.last
911 912 913 914
  end

  def test_create_many
    companies(:first_firm).clients_of_firm.create([{"name" => "Another Client"}, {"name" => "Another Client II"}])
915
    assert_equal 4, companies(:first_firm).clients_of_firm.reload.size
916 917 918
  end

  def test_create_followed_by_save_does_not_load_target
919
    companies(:first_firm).clients_of_firm.create("name" => "Another Client")
920 921 922 923 924 925 926
    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
    companies(:first_firm).clients_of_firm.delete(companies(:first_firm).clients_of_firm.first)
927
    assert_equal 1, companies(:first_firm).clients_of_firm.size
928
    assert_equal 1, companies(:first_firm).clients_of_firm.reload.size
929 930 931 932 933 934 935 936 937 938
  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

939 940 941 942 943
  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.
    ship = Ship.create(name: 'Countless', treasures_count: 10)

944
    assert_not Ship.reflect_on_association(:treasures).has_cached_counter?
945 946 947 948 949 950 951 952 953 954 955 956 957

    # 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
      ship.treasures.create(name: 'Gold')
    end

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

958
  def test_deleting_updates_counter_cache
J
Jon Leighton 已提交
959
    topic = Topic.order("id ASC").first
960 961 962 963 964 965 966
    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

967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
  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

997 998 999 1000 1001 1002 1003 1004 1005
  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

1006
  def test_deleting_updates_counter_cache_without_dependent_option
1007 1008
    post = posts(:welcome)

1009
    assert_difference "post.reload.tags_count", -1 do
1010 1011 1012 1013
      post.taggings.delete(post.taggings.first)
    end
  end

1014 1015
  def test_deleting_updates_counter_cache_with_dependent_delete_all
    post = posts(:welcome)
1016
    post.update_columns(taggings_with_delete_all_count: post.tags_count)
1017 1018 1019 1020 1021 1022

    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

1023 1024
  def test_deleting_updates_counter_cache_with_dependent_destroy
    post = posts(:welcome)
1025
    post.update_columns(taggings_with_destroy_count: post.tags_count)
1026 1027 1028 1029 1030 1031

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

1032 1033 1034 1035 1036 1037 1038
  def test_calling_empty_with_counter_cache
    post = posts(:welcome)
    assert_queries(0) do
      assert_not post.comments.empty?
    end
  end

1039 1040 1041 1042 1043 1044 1045 1046
  def test_custom_named_counter_cache
    topic = topics(:first)

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

1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
  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
    first_reply.update_attributes(:parent_id => nil)
    assert_equal original_count - 1, topic.reload.replies_count

    first_reply.update_attributes(:parent_id => topic.id)
    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

    reply1.update_attributes(:parent_id => topic2.id)
    assert_equal original_count1 - 1, topic1.reload.replies_count
    assert_equal original_count2 + 1, topic2.reload.replies_count

    reply2.update_attributes(:parent_id => topic1.id)
    assert_equal original_count1, topic1.reload.replies_count
    assert_equal original_count2, topic2.reload.replies_count
  end

1078 1079 1080
  def test_deleting_a_collection
    force_signal37_to_load_all_clients_of_firm
    companies(:first_firm).clients_of_firm.create("name" => "Another Client")
1081 1082
    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]])
1083
    assert_equal 0, companies(:first_firm).clients_of_firm.size
1084
    assert_equal 0, companies(:first_firm).clients_of_firm.reload.size
1085 1086 1087 1088
  end

  def test_delete_all
    force_signal37_to_load_all_clients_of_firm
1089 1090
    companies(:first_firm).dependent_clients_of_firm.create("name" => "Another Client")
    clients = companies(:first_firm).dependent_clients_of_firm.to_a
1091
    assert_equal 3, clients.count
1092 1093

    assert_difference "Client.count", -(clients.count) do
1094
      companies(:first_firm).dependent_clients_of_firm.delete_all
1095
    end
1096 1097 1098 1099 1100
  end

  def test_delete_all_with_not_yet_loaded_association_collection
    force_signal37_to_load_all_clients_of_firm
    companies(:first_firm).clients_of_firm.create("name" => "Another Client")
1101
    assert_equal 3, companies(:first_firm).clients_of_firm.size
1102 1103 1104
    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
1105
    assert_equal 0, companies(:first_firm).clients_of_firm.reload.size
1106 1107
  end

1108
  def test_transaction_when_deleting_persisted
J
Jon Leighton 已提交
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
    good = Client.new(:name => "Good")
    bad  = Client.new(:name => "Bad", :raise_on_destroy => true)

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

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

1119
    assert_equal [good, bad], companies(:first_firm).clients_of_firm.reload
1120 1121 1122
  end

  def test_transaction_when_deleting_new_record
1123
    assert_no_queries(ignore_none: false) do
J
Jon Leighton 已提交
1124 1125 1126 1127 1128
      firm = Firm.new
      client = Client.new("name" => "New Client")
      firm.clients_of_firm << client
      firm.clients_of_firm.destroy(client)
    end
1129 1130
  end

1131 1132 1133
  def test_clearing_an_association_collection
    firm = companies(:first_firm)
    client_id = firm.clients_of_firm.first.id
1134
    assert_equal 2, firm.clients_of_firm.size
1135

J
Jon Leighton 已提交
1136
    firm.clients_of_firm.clear
1137 1138

    assert_equal 0, firm.clients_of_firm.size
1139
    assert_equal 0, firm.clients_of_firm.reload.size
1140 1141 1142 1143
    assert_equal [], Client.destroyed_client_ids[firm.id]

    # Should not be destroyed since the association is not dependent.
    assert_nothing_raised do
1144
      assert_nil Client.find(client_id).firm
1145 1146 1147
    end
  end

1148 1149 1150
  def test_clearing_updates_counter_cache
    topic = Topic.first

1151 1152 1153
    assert_difference 'topic.reload.replies_count', -1 do
      topic.replies.clear
    end
1154 1155
  end

1156 1157 1158 1159 1160 1161 1162 1163 1164
  def test_clearing_updates_counter_cache_when_inverse_counter_cache_is_a_symbol_with_dependent_destroy
    car = Car.first
    car.engines.create!

    assert_difference 'car.reload.engines_count', -1 do
      car.engines.clear
    end
  end

1165 1166 1167
  def test_clearing_a_dependent_association_collection
    firm = companies(:first_firm)
    client_id = firm.dependent_clients_of_firm.first.id
1168
    assert_equal 2, firm.dependent_clients_of_firm.size
1169
    assert_equal 1, Client.find_by_id(client_id).client_of
1170

1171
    # :delete_all is called on each client since the dependent options is :destroy
1172 1173 1174
    firm.dependent_clients_of_firm.clear

    assert_equal 0, firm.dependent_clients_of_firm.size
1175
    assert_equal 0, firm.dependent_clients_of_firm.reload.size
1176
    assert_equal [], Client.destroyed_client_ids[firm.id]
1177 1178

    # Should be destroyed since the association is dependent.
1179
    assert_nil Client.find_by_id(client_id)
1180 1181 1182 1183 1184 1185
  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)
1186
    assert_nil Client.find_by_id(client_id)
1187 1188
  end

1189 1190 1191 1192 1193 1194 1195
  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

1196 1197 1198
  def test_clearing_an_exclusively_dependent_association_collection
    firm = companies(:first_firm)
    client_id = firm.exclusively_dependent_clients_of_firm.first.id
1199
    assert_equal 2, firm.exclusively_dependent_clients_of_firm.size
1200 1201 1202 1203 1204 1205 1206 1207

    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
1208
    assert_equal 0, firm.exclusively_dependent_clients_of_firm.reload.size
1209 1210 1211 1212
    # no destroy-filters should have been called
    assert_equal [], Client.destroyed_client_ids[firm.id]

    # Should be destroyed since the association is exclusively dependent.
1213
    assert_nil Client.find_by_id(client_id)
1214 1215 1216 1217 1218 1219 1220
  end

  def test_dependent_association_respects_optional_conditions_on_delete
    firm = companies(:odegy)
    Client.create(:client_of => firm.id, :name => "BigShot Inc.")
    Client.create(:client_of => firm.id, :name => "SmallTime Inc.")
    # only one of two clients is included in the association due to the :conditions key
J
Jon Leighton 已提交
1221
    assert_equal 2, Client.where(client_of: firm.id).size
1222 1223 1224
    assert_equal 1, firm.dependent_conditional_clients_of_firm.size
    firm.destroy
    # only the correctly associated client should have been deleted
J
Jon Leighton 已提交
1225
    assert_equal 1, Client.where(client_of: firm.id).size
1226 1227 1228 1229 1230 1231 1232
  end

  def test_dependent_association_respects_optional_sanitized_conditions_on_delete
    firm = companies(:odegy)
    Client.create(:client_of => firm.id, :name => "BigShot Inc.")
    Client.create(:client_of => firm.id, :name => "SmallTime Inc.")
    # only one of two clients is included in the association due to the :conditions key
J
Jon Leighton 已提交
1233
    assert_equal 2, Client.where(client_of: firm.id).size
1234 1235 1236
    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 已提交
1237
    assert_equal 1, Client.where(client_of: firm.id).size
1238 1239
  end

1240 1241 1242 1243 1244
  def test_dependent_association_respects_optional_hash_conditions_on_delete
    firm = companies(:odegy)
    Client.create(:client_of => firm.id, :name => "BigShot Inc.")
    Client.create(:client_of => firm.id, :name => "SmallTime Inc.")
    # only one of two clients is included in the association due to the :conditions key
J
Jon Leighton 已提交
1245
    assert_equal 2, Client.where(client_of: firm.id).size
1246 1247 1248
    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 已提交
1249
    assert_equal 1, Client.where(client_of: firm.id).size
1250 1251
  end

1252
  def test_delete_all_association_with_primary_key_deletes_correct_records
1253
    firm = Firm.first
1254
    # break the vanilla firm_id foreign key
1255
    assert_equal 3, firm.clients.count
1256
    firm.clients.first.update_columns(firm_id: nil)
1257
    assert_equal 2, firm.clients.reload.count
1258
    assert_equal 2, firm.clients_using_primary_key_with_delete_all.count
1259
    old_record = firm.clients_using_primary_key_with_delete_all.first
1260
    firm = Firm.first
1261
    firm.destroy
1262
    assert_nil Client.find_by_id(old_record.id)
1263
  end
1264

1265 1266
  def test_creation_respects_hash_condition
    ms_client = companies(:first_firm).clients_like_ms_with_hash_conditions.build
1267

1268 1269
    assert        ms_client.save
    assert_equal  'Microsoft', ms_client.name
1270

1271 1272
    another_ms_client = companies(:first_firm).clients_like_ms_with_hash_conditions.create

1273
    assert        another_ms_client.persisted?
1274 1275 1276 1277 1278 1279 1280 1281 1282
    assert_equal  'Microsoft', another_ms_client.name
  end

  def test_clearing_without_initial_access
    firm = companies(:first_firm)

    firm.clients_of_firm.clear

    assert_equal 0, firm.clients_of_firm.size
1283
    assert_equal 0, firm.clients_of_firm.reload.size
1284 1285 1286 1287
  end

  def test_deleting_a_item_which_is_not_in_the_collection
    force_signal37_to_load_all_clients_of_firm
1288
    summit = Client.find_by_name('Summit')
1289
    companies(:first_firm).clients_of_firm.delete(summit)
1290
    assert_equal 2, companies(:first_firm).clients_of_firm.size
1291
    assert_equal 2, companies(:first_firm).clients_of_firm.reload.size
1292 1293 1294
    assert_equal 2, summit.client_of
  end

1295
  def test_deleting_by_fixnum_id
1296
    david = Developer.find(1)
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312

    assert_difference 'david.projects.count', -1 do
      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)

    assert_difference 'david.projects.count', -1 do
      assert_equal 1, david.projects.delete('1').size
    end

    assert_equal 1, david.projects.size
1313 1314 1315 1316 1317
  end

  def test_deleting_self_type_mismatch
    david = Developer.find(1)
    david.projects.reload
1318
    assert_raise(ActiveRecord::AssociationTypeMismatch) { david.projects.delete(Project.find(1).developers) }
1319 1320
  end

1321 1322 1323 1324 1325 1326 1327
  def test_destroying
    force_signal37_to_load_all_clients_of_firm

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

1328
    assert_equal 1, companies(:first_firm).reload.clients_of_firm.size
1329
    assert_equal 1, companies(:first_firm).clients_of_firm.reload.size
1330 1331
  end

1332 1333 1334 1335 1336 1337 1338
  def test_destroying_by_fixnum_id
    force_signal37_to_load_all_clients_of_firm

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

1339
    assert_equal 1, companies(:first_firm).reload.clients_of_firm.size
1340
    assert_equal 1, companies(:first_firm).clients_of_firm.reload.size
1341 1342 1343 1344 1345 1346 1347 1348 1349
  end

  def test_destroying_by_string_id
    force_signal37_to_load_all_clients_of_firm

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

1350
    assert_equal 1, companies(:first_firm).reload.clients_of_firm.size
1351
    assert_equal 1, companies(:first_firm).clients_of_firm.reload.size
1352 1353
  end

1354 1355 1356
  def test_destroying_a_collection
    force_signal37_to_load_all_clients_of_firm
    companies(:first_firm).clients_of_firm.create("name" => "Another Client")
1357
    assert_equal 3, companies(:first_firm).clients_of_firm.size
1358 1359 1360 1361 1362

    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

1363
    assert_equal 1, companies(:first_firm).reload.clients_of_firm.size
1364
    assert_equal 1, companies(:first_firm).clients_of_firm.reload.size
1365 1366
  end

1367 1368
  def test_destroy_all
    force_signal37_to_load_all_clients_of_firm
1369 1370 1371 1372
    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)
1373
    assert destroyed.all?(&:frozen?), "destroyed clients should be frozen"
1374
    assert companies(:first_firm).clients_of_firm.empty?, "37signals has no clients after destroy all"
1375
    assert companies(:first_firm).clients_of_firm.reload.empty?, "37signals has no clients after destroy all and refresh"
1376 1377 1378 1379
  end

  def test_dependence
    firm = companies(:first_firm)
1380
    assert_equal 3, firm.clients.size
1381
    firm.destroy
1382
    assert Client.all.merge!(:where => "firm_id=#{firm.id}").to_a.empty?
1383 1384
  end

1385 1386 1387 1388 1389
  def test_dependence_for_associations_with_hash_condition
    david = authors(:david)
    assert_difference('Post.count', -1) { assert david.destroy }
  end

1390
  def test_destroy_dependent_when_deleted_from_association
1391
    # sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first
1392
    firm = Firm.all.merge!(:order => "id").first
1393
    assert_equal 3, firm.clients.size
1394 1395 1396 1397 1398 1399

    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) }
1400
    assert_equal 2, firm.clients.size
1401 1402 1403 1404 1405
  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"
1406
    reply.replies.create "title" => "neat and simple", "content" => "ain't complaining"
1407 1408 1409 1410 1411 1412 1413

    assert_nothing_raised { topic.destroy }
  end

  def test_dependence_with_transaction_support_on_failure
    firm = companies(:first_firm)
    clients = firm.clients
1414
    assert_equal 3, clients.length
1415
    clients.last.instance_eval { def overwrite_to_raise() raise "Trigger rollback" end }
1416 1417 1418

    firm.destroy rescue "do nothing"

1419
    assert_equal 3, Client.all.merge!(:where => "firm_id=#{firm.id}").to_a.size
1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
  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

1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
  def test_restrict_with_exception
    firm = RestrictedWithExceptionFirm.create!(:name => 'restrict')
    firm.companies.create(:name => 'child')

    assert !firm.companies.empty?
    assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
    assert RestrictedWithExceptionFirm.exists?(:name => 'restrict')
    assert firm.companies.exists?(:name => 'child')
  end

1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471
  def test_restrict_with_error_is_deprecated_using_key_many
    I18n.backend = I18n::Backend::Simple.new
    I18n.backend.store_translations :en, activerecord: { errors: { messages: { restrict_dependent_destroy: { many: 'message for deprecated key' } } } }

    firm = RestrictedWithErrorFirm.create!(name: 'restrict')
    firm.companies.create(name: 'child')

    assert !firm.companies.empty?

    assert_deprecated { firm.destroy }

    assert !firm.errors.empty?

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

1472 1473
  def test_restrict_with_error
    firm = RestrictedWithErrorFirm.create!(:name => 'restrict')
1474 1475 1476 1477 1478 1479 1480 1481
    firm.companies.create(:name => 'child')

    assert !firm.companies.empty?

    firm.destroy

    assert !firm.errors.empty?

1482
    assert_equal "Cannot delete record because dependent companies exist", firm.errors[:base].first
1483
    assert RestrictedWithErrorFirm.exists?(:name => 'restrict')
1484
    assert firm.companies.exists?(:name => 'child')
1485 1486
  end

1487 1488 1489
  def test_restrict_with_error_with_locale
    I18n.backend = I18n::Backend::Simple.new
    I18n.backend.store_translations 'en', activerecord: {attributes: {restricted_with_error_firm: {companies: 'client companies'}}}
1490 1491
    firm = RestrictedWithErrorFirm.create!(name: 'restrict')
    firm.companies.create(name: 'child')
1492 1493 1494 1495 1496 1497 1498 1499

    assert !firm.companies.empty?

    firm.destroy

    assert !firm.errors.empty?

    assert_equal "Cannot delete record because dependent client companies exist", firm.errors[:base].first
1500 1501
    assert RestrictedWithErrorFirm.exists?(name: 'restrict')
    assert firm.companies.exists?(name: 'child')
1502 1503 1504 1505
  ensure
    I18n.backend.reload!
  end

1506
  def test_included_in_collection
1507
    assert_equal true, companies(:first_firm).clients.include?(Client.find(2))
1508 1509
  end

1510 1511 1512
  def test_included_in_collection_for_new_records
    client = Client.create(:name => 'Persisted')
    assert_nil client.client_of
1513 1514
    assert_equal false, Firm.new.clients_of_firm.include?(client),
     'includes a client that does not belong to any firm'
1515 1516
  end

1517
  def test_adding_array_and_collection
J
Jon Leighton 已提交
1518
    assert_nothing_raised { Firm.first.clients + Firm.all.last.clients }
1519 1520 1521
  end

  def test_replace_with_less
1522
    firm = Firm.all.merge!(:order => "id").first
1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535
    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
1536
    firm = Firm.all.merge!(:order => "id").first
1537 1538 1539 1540
    firm.clients = [companies(:second_client), Client.new("name" => "New Client")]
    firm.save
    firm.reload
    assert_equal 2, firm.clients.length
1541
    assert_equal false, firm.clients.include?(:first_client)
1542 1543
  end

1544 1545 1546 1547 1548 1549 1550
  def test_replace_failure
    firm = companies(:first_firm)
    account = Account.new
    orig_accounts = firm.accounts.to_a

    assert !account.valid?
    assert !orig_accounts.empty?
1551
    error = assert_raise ActiveRecord::RecordNotSaved do
1552 1553
      firm.accounts = [account]
    end
1554

1555
    assert_equal orig_accounts, firm.accounts
1556 1557
    assert_equal "Failed to replace accounts because one or more of the " \
                 "new records could not be saved.", error.message
1558 1559
  end

1560 1561 1562 1563 1564 1565 1566 1567
  def test_replace_with_same_content
    firm = Firm.first
    firm.clients = []
    firm.save

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

    assert_equal [], firm.send('clients=', [])
1570 1571
  end

1572
  def test_transactions_when_replacing_on_persisted
J
Jon Leighton 已提交
1573 1574
    good = Client.new(:name => "Good")
    bad  = Client.new(:name => "Bad", :raise_on_save => true)
1575

J
Jon Leighton 已提交
1576 1577 1578 1579 1580 1581 1582
    companies(:first_firm).clients_of_firm = [good]

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

1583
    assert_equal [good], companies(:first_firm).clients_of_firm.reload
1584 1585 1586
  end

  def test_transactions_when_replacing_on_new_record
1587
    assert_no_queries(ignore_none: false) do
J
Jon Leighton 已提交
1588 1589 1590
      firm = Firm.new
      firm.clients_of_firm = [Client.new("name" => "New Client")]
    end
1591 1592
  end

1593
  def test_get_ids
1594
    assert_equal [companies(:first_client).id, companies(:second_client).id, companies(:another_first_firm_client).id], companies(:first_firm).client_ids
1595 1596
  end

1597 1598
  def test_get_ids_for_loaded_associations
    company = companies(:first_firm)
1599
    company.clients.reload
1600 1601 1602 1603 1604 1605 1606 1607 1608
    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?
1609
    assert_equal [companies(:first_client).id, companies(:second_client).id, companies(:another_first_firm_client).id], company.client_ids
1610 1611 1612
    assert !company.clients.loaded?
  end

1613 1614 1615 1616
  def test_get_ids_ignores_include_option
    assert_equal [readers(:michael_welcome).id], posts(:welcome).readers_with_person_ids
  end

1617
  def test_get_ids_for_ordered_association
1618
    assert_equal [companies(:another_first_firm_client).id, companies(:second_client).id, companies(:first_client).id], companies(:first_firm).clients_ordered_by_name_ids
1619 1620
  end

1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
  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!
1636
    Contract.create! # another contract
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
    company = Company.new(:name => "Some Company")

    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

1648 1649 1650 1651 1652
  def test_assign_ids_ignoring_blanks
    firm = Firm.create!(:name => 'Apple')
    firm.client_ids = [companies(:first_client).id, nil, companies(:second_client).id, '']
    firm.save!

1653
    assert_equal 2, firm.clients.reload.size
1654
    assert_equal true, firm.clients.include?(companies(:second_client))
1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
  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)] },
      lambda { authors(:mary).comments << Comment.create!(:body => "Yay", :post_id => 424242) },
      lambda { authors(:mary).comments.delete(authors(:mary).comments.first) },
1667
    ].each {|block| assert_raise(ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection, &block) }
1668 1669 1670
  end

  def test_dynamic_find_should_respect_association_order_for_through
1671
    assert_equal Comment.find(10), authors(:david).comments_desc.where("comments.type = 'SpecialComment'").first
1672
    assert_equal Comment.find(10), authors(:david).comments_desc.find_by_type('SpecialComment')
1673 1674 1675 1676 1677 1678 1679 1680 1681
  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 已提交
1682
    firm.clients.load_target
1683

1684 1685 1686 1687
    client = firm.clients.first

    assert_no_queries do
      assert firm.clients.loaded?
1688
      assert_equal true, firm.clients.include?(client)
1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
    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
1699
      assert_equal true, firm.clients.include?(client)
1700 1701 1702 1703 1704 1705 1706 1707 1708
    end
    assert ! firm.clients.loaded?
  end

  def test_include_returns_false_for_non_matching_record_to_verify_scoping
    firm = companies(:first_firm)
    client = Client.create!(:name => 'Not Associated')

    assert ! firm.clients.loaded?
1709
    assert_equal false, firm.clients.include?(client)
1710 1711
  end

1712
  def test_calling_first_nth_or_last_on_association_should_not_load_association
1713 1714
    firm = companies(:first_firm)
    firm.clients.first
1715
    firm.clients.second
1716 1717 1718 1719 1720 1721
    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 已提交
1722
    firm.clients.load_target
1723 1724
    assert firm.clients.loaded?

1725
    assert_no_queries(ignore_none: false) do
1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739
      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)
    firm.clients.build(:name => 'Foo')
    assert !firm.clients.loaded?

    assert_queries 1 do
      firm.clients.first
1740
      firm.clients.second
1741 1742 1743 1744 1745 1746
      firm.clients.last
    end

    assert firm.clients.loaded?
  end

1747
  def test_calling_first_nth_or_last_on_existing_record_with_create_should_not_load_association
1748 1749 1750 1751
    firm = companies(:first_firm)
    firm.clients.create(:name => 'Foo')
    assert !firm.clients.loaded?

1752
    assert_queries 3 do
1753
      firm.clients.first
1754
      firm.clients.second
1755 1756 1757 1758 1759 1760
      firm.clients.last
    end

    assert !firm.clients.loaded?
  end

1761
  def test_calling_first_nth_or_last_on_new_record_should_not_run_queries
1762 1763 1764 1765
    firm = Firm.new

    assert_no_queries do
      firm.clients.first
1766
      firm.clients.second
1767 1768 1769
      firm.clients.last
    end
  end
1770

1771
  def test_calling_first_or_last_with_integer_on_association_should_not_load_association
1772
    firm = companies(:first_firm)
1773 1774
    firm.clients.create(:name => 'Foo')
    assert !firm.clients.loaded?
1775

1776
    assert_queries 2 do
1777 1778 1779 1780
      firm.clients.first(2)
      firm.clients.last(2)
    end

1781
    assert !firm.clients.loaded?
1782 1783
  end

1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819
  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?
1820
    assert_equal 3, firm.clients.size
1821 1822
  end

1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898
  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

1899 1900 1901 1902 1903 1904 1905
  def test_joins_with_namespaced_model_should_use_correct_type
    old = ActiveRecord::Base.store_full_sti_class
    ActiveRecord::Base.store_full_sti_class = true

    firm = Namespaced::Firm.create({ :name => 'Some Company' })
    firm.clients.create({ :name => 'Some Client' })

1906
    stats = Namespaced::Firm.all.merge!(
1907
      :select => "#{Namespaced::Firm.table_name}.id, COUNT(#{Namespaced::Client.table_name}.id) AS num_clients",
1908 1909
      :joins  => :clients,
      :group  => "#{Namespaced::Firm.table_name}.id"
J
Jon Leighton 已提交
1910
    ).find firm.id
1911 1912 1913 1914 1915
    assert_equal 1, stats.num_clients.to_i
  ensure
    ActiveRecord::Base.store_full_sti_class = old
  end

1916 1917
  def test_association_proxy_transaction_method_starts_transaction_in_association_class
    Comment.expects(:transaction)
1918
    Post.first.comments.transaction do
1919
      # nothing
1920 1921 1922
    end
  end

1923
  def test_sending_new_to_association_proxy_should_have_same_effect_as_calling_new
1924 1925 1926 1927 1928 1929 1930 1931
    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)
1932
  end
1933 1934

  def test_creating_using_primary_key
1935
    firm = Firm.all.merge!(:order => "id").first
1936 1937 1938
    client = firm.clients_using_primary_key.create!(:name => 'test')
    assert_equal firm.name, client.firm_name
  end
1939 1940 1941

  def test_defining_has_many_association_with_delete_all_dependency_lazily_evaluates_target_class
    ActiveRecord::Reflection::AssociationReflection.any_instance.expects(:class_name).never
1942
    class_eval(<<-EOF, __FILE__, __LINE__ + 1)
1943 1944 1945 1946 1947 1948 1949 1950
      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
1951
    class_eval(<<-EOF, __FILE__, __LINE__ + 1)
1952 1953 1954 1955 1956
      class NullifyModel < ActiveRecord::Base
        has_many :nonentities, :dependent => :nullify
      end
    EOF
  end
1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968

  def test_attributes_are_being_set_when_initialized_from_has_many_association_with_where_clause
    new_comment = posts(:welcome).comments.where(:body => "Some content").build
    assert_equal new_comment.body, "Some content"
  end

  def test_attributes_are_being_set_when_initialized_from_has_many_association_with_multiple_where_clauses
    new_comment = posts(:welcome).comments.where(:body => "Some content").where(:type => 'SpecialComment').build
    assert_equal new_comment.body, "Some content"
    assert_equal new_comment.type, "SpecialComment"
    assert_equal new_comment.post_id, posts(:welcome).id
  end
1969 1970 1971 1972

  def test_include_method_in_has_many_association_should_return_true_for_instance_added_with_build
    post = Post.new
    comment = post.comments.build
1973
    assert_equal true, post.comments.include?(comment)
1974
  end
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995

  def test_load_target_respects_protected_attributes
    topic = Topic.create!
    reply = topic.replies.create(:title => "reply 1")
    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
1996 1997 1998 1999 2000 2001 2002

  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
2003 2004 2005 2006 2007 2008 2009 2010 2011 2012

  def test_merging_with_custom_attribute_writer
    bulb = Bulb.new(:color => "red")
    assert_equal "RED!", bulb.color

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

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

2014 2015 2016 2017 2018
  def test_abstract_class_with_polymorphic_has_many
    post = SubStiPost.create! :title => "fooo", :body => "baa"
    tagging = Tagging.create! :taggable => post
    assert_equal [tagging], post.taggings
  end
F
Farley Knight 已提交
2019

2020 2021 2022 2023 2024 2025 2026 2027 2028
  def test_with_polymorphic_has_many_with_custom_columns_name
    post = Post.create! :title => 'foo', :body => 'bar'
    image = Image.create!

    post.images << image

    assert_equal [image], post.images
  end

A
Andy Lindeman 已提交
2029
  def test_build_with_polymorphic_has_many_does_not_allow_to_override_type_and_id
2030 2031 2032 2033 2034 2035 2036
    welcome = posts(:welcome)
    tagging = welcome.taggings.build(:taggable_id => 99, :taggable_type => 'ShouldNotChange')

    assert_equal welcome.id, tagging.taggable_id
    assert_equal 'Post', tagging.taggable_type
  end

F
Farley Knight 已提交
2037 2038 2039 2040 2041 2042 2043
  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
2044 2045 2046 2047 2048 2049 2050

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

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

2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067
  def test_attributes_are_set_when_initialized_from_has_many_null_relationship
    car  = Car.new name: 'honda'
    bulb = car.bulbs.where(name: 'headlight').first_or_initialize
    assert_equal 'headlight', bulb.name
  end

  def test_attributes_are_set_when_initialized_from_polymorphic_has_many_null_relationship
    post    = Post.new title: 'title', body: 'bar'
    tag     = Tag.create!(name: 'foo')

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

    assert_equal tag.id, tagging.tag_id
    assert_equal 'Post', tagging.taggable_type
  end

2068 2069 2070 2071 2072 2073 2074 2075 2076 2077
  def test_replace
    car = Car.create(:name => 'honda')
    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
2078

2079
  def test_replace_returns_target
2080 2081 2082 2083 2084 2085
    car = Car.create(:name => 'honda')
    bulb1 = car.bulbs.create
    bulb2 = car.bulbs.create
    bulb3 = Bulb.create

    assert_equal [bulb1, bulb2], car.bulbs
2086
    result = car.bulbs.replace([bulb3, bulb1])
2087 2088 2089 2090
    assert_equal [bulb1, bulb3], car.bulbs
    assert_equal [bulb1, bulb3], result
  end

2091 2092 2093 2094
  def test_collection_association_with_private_kernel_method
    firm = companies(:first_firm)
    assert_equal [accounts(:signals37)], firm.accounts.open
  end
J
Jon Leighton 已提交
2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108

  test "first_or_initialize adds the record to the association" do
    firm = Firm.create! name: 'omg'
    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
    firm = Firm.create! name: 'omg'
    firm.clients_of_firm.load_target
    client = firm.clients_of_firm.first_or_create name: 'lol'
    assert_equal [client], firm.clients_of_firm
    assert_equal [client], firm.reload.clients_of_firm
  end
2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120

  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
2121

2122 2123 2124
  test "has many associations on new records use null relations" do
    post = Post.new

2125
    assert_no_queries(ignore_none: false) do
2126 2127
      assert_equal [], post.comments
      assert_equal [], post.comments.where(body: 'omg')
2128
      assert_equal [], post.comments.pluck(:body)
2129
      assert_equal 0,  post.comments.sum(:id)
V
Vipul A M 已提交
2130
      assert_equal 0,  post.comments.count
2131 2132
    end
  end
2133 2134 2135 2136 2137

  test "collection proxy respects default scope" do
    author = authors(:mary)
    assert !author.first_posts.exists?
  end
J
Jon Leighton 已提交
2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149

  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
2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165

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

    post = david.posts.first
    post.type = 'PostWithSpecialCategorization'
    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
2166 2167 2168

  test "does not duplicate associations when used with natural primary keys" do
    speedometer = Speedometer.create!(id: '4')
R
Rafael Mendonça França 已提交
2169
    speedometer.minivans.create!(minivan_id: 'a-van-red' ,name: 'a van', color: 'red')
2170 2171 2172 2173

    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 已提交
2174 2175 2176 2177 2178 2179 2180 2181 2182

  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
2183

2184 2185 2186 2187 2188 2189 2190 2191
  test 'unscopes the default scope of associated model when used with include' do
    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

2192 2193 2194 2195
  test "raises RecordNotDestroyed when replaced child can't be destroyed" do
    car = Car.create!
    original_child = FailedBulb.create!(car: car)

2196
    error = assert_raise(ActiveRecord::RecordNotDestroyed) do
2197 2198 2199 2200
      car.failed_bulbs = [FailedBulb.create!]
    end

    assert_equal [original_child], car.reload.failed_bulbs
2201
    assert_equal "Failed to destroy the record", error.message
2202
  end
2203

2204 2205 2206 2207 2208 2209
  test 'updates counter cache when default scope is given' do
    topic = DefaultRejectedTopic.create approved: true

    assert_difference "topic.reload.replies_count", 1 do
      topic.approved_replies.create!
    end
2210
  end
2211 2212 2213 2214 2215 2216 2217 2218 2219 2220

  test 'dangerous association name raises ArgumentError' do
    [:errors, 'errors', :save, 'save'].each do |name|
      assert_raises(ArgumentError, "Association #{name} should not be allowed") do
        Class.new(ActiveRecord::Base) do
          has_many name
        end
      end
    end
  end
2221

2222
  test 'passes custom context validation to validate children' do
2223 2224
    pirate = FamousPirate.new
    pirate.famous_ships << ship = FamousShip.new
2225 2226 2227

    assert pirate.valid?
    assert_not pirate.valid?(:conference)
2228 2229
    assert_equal "can't be blank", ship.errors[:name].first
  end
2230 2231 2232 2233 2234 2235 2236 2237 2238 2239

  test 'association with instance dependent scope' do
    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
2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252

  test 'associations autosaves when object is already persited' do
    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
2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316

  test 'associations replace in memory when records have the same id' do
    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

  test 'in memory replacement executes no queries' do
    bulb = Bulb.create!
    car = Car.create!(bulbs: [bulb])

    new_bulb = Bulb.find(bulb.id)

    assert_no_queries do
      car.bulbs = [new_bulb]
    end
  end

  test 'in memory replacements do not execute callbacks' do
    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

  test 'in memory replacements sets inverse instance' do
    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

  test 'in memory replacement maintains order' do
    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
2317 2318 2319 2320 2321 2322

  def test_association_force_reload_with_only_true_is_deprecated
    company = Company.find(1)

    assert_deprecated { company.clients_of_firm(true) }
  end
2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352

  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
2353 2354 2355 2356 2357 2358 2359 2360

  def test_ids_reader_memoization
    car = Car.create!(name: 'Tofaş')
    bulb = Bulb.create!(car: car)

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