has_many_associations_test.rb 55.5 KB
Newer Older
1
require "cases/helper"
2 3 4
require 'models/developer'
require 'models/project'
require 'models/company'
F
Farley Knight 已提交
5
require 'models/contract'
6 7 8 9 10
require 'models/topic'
require 'models/reply'
require 'models/category'
require 'models/post'
require 'models/author'
11
require 'models/essay'
12 13 14
require 'models/comment'
require 'models/person'
require 'models/reader'
J
Jeremy Kemper 已提交
15
require 'models/tagging'
16
require 'models/tag'
17 18
require 'models/invoice'
require 'models/line_item'
19 20
require 'models/car'
require 'models/bulb'
21
require 'models/engine'
22

23 24
class HasManyAssociationsTestForCountWithFinderSql < ActiveRecord::TestCase
  class Invoice < ActiveRecord::Base
25 26 27
    ActiveSupport::Deprecation.silence do
      has_many :custom_line_items, :class_name => 'LineItem', :finder_sql => "SELECT line_items.* from line_items"
    end
28 29 30 31 32 33 34 35 36 37
  end
  def test_should_fail
    assert_raise(ArgumentError) do
      Invoice.create.custom_line_items.count(:conditions => {:amount => 0})
    end
  end
end

class HasManyAssociationsTestForCountWithCountSql < ActiveRecord::TestCase
  class Invoice < ActiveRecord::Base
38 39 40
    ActiveSupport::Deprecation.silence do
      has_many :custom_line_items, :class_name => 'LineItem', :counter_sql => "SELECT COUNT(*) line_items.* from line_items"
    end
41 42 43 44 45 46 47 48
  end
  def test_should_fail
    assert_raise(ArgumentError) do
      Invoice.create.custom_line_items.count(:conditions => {:amount => 0})
    end
  end
end

49
class HasManyAssociationsTestForCountWithVariousFinderSqls < ActiveRecord::TestCase
50
  class Invoice < ActiveRecord::Base
51 52
    ActiveSupport::Deprecation.silence do
      has_many :custom_line_items, :class_name => 'LineItem', :finder_sql => "SELECT DISTINCT line_items.amount from line_items"
53 54 55
      has_many :custom_full_line_items, :class_name => 'LineItem', :finder_sql => "SELECT line_items.invoice_id, line_items.amount from line_items"
      has_many :custom_star_line_items, :class_name => 'LineItem', :finder_sql => "SELECT * from line_items"
      has_many :custom_qualified_star_line_items, :class_name => 'LineItem', :finder_sql => "SELECT line_items.* from line_items"
56
    end
57 58 59 60 61 62 63 64 65 66
  end

  def test_should_count_distinct_results
    invoice = Invoice.new
    invoice.custom_line_items << LineItem.new(:amount => 0)
    invoice.custom_line_items << LineItem.new(:amount => 0)
    invoice.save!

    assert_equal 1, invoice.custom_line_items.count
  end
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

  def test_should_count_results_with_multiple_fields
    invoice = Invoice.new
    invoice.custom_full_line_items << LineItem.new(:amount => 0)
    invoice.custom_full_line_items << LineItem.new(:amount => 0)
    invoice.save!

    assert_equal 2, invoice.custom_full_line_items.count
  end

  def test_should_count_results_with_star
    invoice = Invoice.new
    invoice.custom_star_line_items << LineItem.new(:amount => 0)
    invoice.custom_star_line_items << LineItem.new(:amount => 0)
    invoice.save!

    assert_equal 2, invoice.custom_star_line_items.count
  end

  def test_should_count_results_with_qualified_star
    invoice = Invoice.new
    invoice.custom_qualified_star_line_items << LineItem.new(:amount => 0)
    invoice.custom_qualified_star_line_items << LineItem.new(:amount => 0)
    invoice.save!

    assert_equal 2, invoice.custom_qualified_star_line_items.count
  end
94 95
end

96 97 98 99 100 101 102 103 104 105
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
    assert author.posts_with_comments_sorted_by_comment_id.where('comments.id > 0').reorder('posts.comments_count DESC', 'posts.taggings_count DESC').last
  end
end
106

107 108 109

class HasManyAssociationsTest < ActiveRecord::TestCase
  fixtures :accounts, :categories, :companies, :developers, :projects,
110
           :developers_projects, :topics, :authors, :comments,
111
           :people, :posts, :readers, :taggings, :cars, :essays
112 113 114 115 116

  def setup
    Client.destroyed_client_ids.clear
  end

117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
  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

134 135 136 137 138 139 140 141 142 143 144 145 146
  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

147
  def test_association_keys_bypass_attribute_protection
148 149 150 151 152
    car = Car.create(:name => 'honda')

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

153 154 155
    bulb = car.bulbs.new :car_id => car.id + 1
    assert_equal car.id, bulb.car_id

156 157 158
    bulb = car.bulbs.build
    assert_equal car.id, bulb.car_id

159 160 161
    bulb = car.bulbs.build :car_id => car.id + 1
    assert_equal car.id, bulb.car_id

162 163
    bulb = car.bulbs.create
    assert_equal car.id, bulb.car_id
164 165 166

    bulb = car.bulbs.create :car_id => car.id + 1
    assert_equal car.id, bulb.car_id
167 168
  end

169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
  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

191 192 193 194
  # 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)
195
    scoped_count = car.foo_bulbs.where_values.count
196

197 198
    bulb = car.foo_bulbs.build
    assert_not_equal scoped_count, bulb.scope_after_initialize.where_values.count
199

200 201
    bulb = car.foo_bulbs.create
    assert_not_equal scoped_count, bulb.scope_after_initialize.where_values.count
202

203 204
    bulb = car.foo_bulbs.create!
    assert_not_equal scoped_count, bulb.scope_after_initialize.where_values.count
205 206
  end

207
  def test_no_sql_should_be_fired_if_association_already_loaded
A
Aaron Patterson 已提交
208
    Car.create(:name => 'honda')
209
    bulbs = Car.first.bulbs
B
Brian Cardarella 已提交
210
    bulbs.to_a # to load all instances of bulbs
211

212 213 214 215
    assert_no_queries do
      bulbs.first()
      bulbs.first({})
    end
216 217 218 219 220

    assert_no_queries do
      bulbs.last()
      bulbs.last({})
    end
221 222
  end

223 224 225
  def test_create_resets_cached_counters
    person = Person.create!(:first_name => 'tenderlove')
    post   = Post.first
226 227

    assert_equal [], person.readers
228
    assert_nil person.readers.find_by_post_id(post.id)
229

230
    person.readers.create(:post_id => post.id)
231 232 233 234 235 236 237

    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

238 239 240 241
  def force_signal37_to_load_all_clients_of_firm
    companies(:first_firm).clients_of_firm.each {|f| }
  end

242
  # sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first
243
  def test_counting_with_counter_sql
244
    assert_equal 2, Firm.all.merge!(:order => "id").first.clients.count
245 246 247
  end

  def test_counting
248
    assert_equal 2, Firm.all.merge!(:order => "id").first.plain_clients.count
249 250 251
  end

  def test_counting_with_single_hash
252
    assert_equal 1, Firm.all.merge!(:order => "id").first.plain_clients.where(:name => "Microsoft").count
253 254 255
  end

  def test_counting_with_column_name_and_hash
256
    assert_equal 2, Firm.all.merge!(:order => "id").first.plain_clients.count(:name)
257 258
  end

259 260 261 262 263 264
  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

265
  def test_finding
266
    assert_equal 2, Firm.all.merge!(:order => "id").first.clients.length
267 268
  end

269 270 271 272
  def test_finding_array_compatibility
    assert_equal 2, Firm.order(:id).find{|f| f.id > 0}.clients.length
  end

273 274
  def test_find_with_blank_conditions
    [[], {}, nil, ""].each do |blank|
275
      assert_equal 2, Firm.all.merge!(:order => "id").first.clients.where(blank).to_a.size
276 277 278
    end
  end

279 280
  def test_find_many_with_merged_options
    assert_equal 1, companies(:first_firm).limited_clients.size
281 282
    assert_equal 1, companies(:first_firm).limited_clients.to_a.size
    assert_equal 2, companies(:first_firm).limited_clients.limit(nil).to_a.size
283 284
  end

285
  def test_find_should_prepend_to_association_order
286
    ordered_clients =  companies(:first_firm).clients_sorted_desc.order('companies.id')
287
    assert_equal ['companies.id', 'id DESC'], ordered_clients.order_values
288 289
  end

290
  def test_dynamic_find_should_respect_association_order
291
    assert_equal companies(:second_client), companies(:first_firm).clients_sorted_desc.where("type = 'Client'").first
292 293 294 295 296 297 298 299 300
    assert_equal companies(:second_client), companies(:first_firm).clients_sorted_desc.find_by_type('Client')
  end

  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
301
    assert_equal "Summit", Firm.all.merge!(:order => "id").first.clients.first.name
302 303 304
  end

  def test_finding_with_different_class_name_and_order
305
    assert_equal "Microsoft", Firm.all.merge!(:order => "id").first.clients_sorted_desc.first.name
306 307 308
  end

  def test_finding_with_foreign_key
309
    assert_equal "Microsoft", Firm.all.merge!(:order => "id").first.clients_of_firm.first.name
310 311 312
  end

  def test_finding_with_condition
313
    assert_equal "Microsoft", Firm.all.merge!(:order => "id").first.clients_like_ms.first.name
314 315 316
  end

  def test_finding_with_condition_hash
317
    assert_equal "Microsoft", Firm.all.merge!(:order => "id").first.clients_like_ms_with_hash_conditions.first.name
318 319
  end

320
  def test_finding_using_primary_key
321
    assert_equal "Summit", Firm.all.merge!(:order => "id").first.clients_using_primary_key.first.name
322 323
  end

324
  def test_finding_using_sql
325
    firm = Firm.order("id").first
326 327 328 329
    first_client = firm.clients_using_sql.first
    assert_not_nil first_client
    assert_equal "Microsoft", first_client.name
    assert_equal 1, firm.clients_using_sql.size
330
    assert_equal 1, Firm.order("id").first.clients_using_sql.size
331 332 333
  end

  def test_finding_using_sql_take_into_account_only_uniq_ids
334
    firm = Firm.order("id").first
335 336 337 338 339 340
    client = firm.clients_using_sql.first
    assert_equal client, firm.clients_using_sql.find(client.id, client.id)
    assert_equal client, firm.clients_using_sql.find(client.id, client.id.to_s)
  end

  def test_counting_using_sql
341 342 343 344
    assert_equal 1, Firm.order("id").first.clients_using_counter_sql.size
    assert Firm.order("id").first.clients_using_counter_sql.any?
    assert_equal 0, Firm.order("id").first.clients_using_zero_counter_sql.size
    assert !Firm.order("id").first.clients_using_zero_counter_sql.any?
345 346 347
  end

  def test_counting_non_existant_items_using_sql
348
    assert_equal 0, Firm.order("id").first.no_clients_using_counter_sql.size
349 350 351 352 353 354
  end

  def test_counting_using_finder_sql
    assert_equal 2, Firm.find(4).clients_using_sql.count
  end

355 356 357 358
  def test_belongs_to_sanity
    c = Client.new
    assert_nil c.firm

359
    flunk "belongs_to failed if check" if c.firm
360 361 362
  end

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

365
    assert_raise(ActiveRecord::RecordNotFound) { firm.clients.find }
366 367 368 369 370 371 372 373 374 375 376 377 378

    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

379
    assert_raise(ActiveRecord::RecordNotFound) { firm.clients.find(2, 99) }
380 381
  end

382
  def test_find_string_ids_when_using_finder_sql
383
    firm = Firm.order("id").first
384 385 386 387 388 389 390 391 392 393 394 395 396 397

    client = firm.clients_using_finder_sql.find("2")
    assert_kind_of Client, client

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

    client_ary = firm.clients_using_finder_sql.find("2", "3")
    assert_kind_of Array, client_ary
    assert_equal 2, client_ary.size
    assert client_ary.include?(client)
  end

398
  def test_find_all
399 400 401
    firm = Firm.all.merge!(:order => "id").first
    assert_equal 2, firm.clients.where("#{QUOTED_TYPE} = 'Client'").to_a.length
    assert_equal 1, firm.clients.where("name = 'Summit'").to_a.length
402 403
  end

404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
  def test_find_each
    firm = companies(:first_firm)

    assert ! firm.clients.loaded?

    assert_queries(3) do
      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
420
      firm.clients.where(name: 'Microsoft').find_each(batch_size: 1) do |c|
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
        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

443
  def test_find_all_sanitized
444
    # sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first
445 446 447 448
    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
449 450 451
  end

  def test_find_first
452
    firm = Firm.all.merge!(:order => "id").first
453
    client2 = Client.find(2)
454 455
    assert_equal firm.clients.first, firm.clients.order("id").first
    assert_equal client2, firm.clients.where("#{QUOTED_TYPE} = 'Client'").order("id").first
456 457 458
  end

  def test_find_first_sanitized
459
    firm = Firm.all.merge!(:order => "id").first
460
    client2 = Client.find(2)
461 462
    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
463 464
  end

465 466
  def test_find_all_with_include_and_conditions
    assert_nothing_raised do
467
      Developer.all.merge!(:joins => :audit_logs, :where => {'audit_logs.message' => nil, :name => 'Smith'}).to_a
468 469 470
    end
  end

471 472
  def test_find_in_collection
    assert_equal Client.find(2).name, companies(:first_firm).clients.find(2).name
473
    assert_raise(ActiveRecord::RecordNotFound) { companies(:first_firm).clients.find(6) }
474 475 476
  end

  def test_find_grouped
477 478
    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
479 480 481 482
    assert_equal 2, all_clients_of_firm1.size
    assert_equal 1, grouped_clients_of_firm1.size
  end

483
  def test_find_scoped_grouped
484
    assert_equal 1, companies(:first_firm).clients_grouped_by_firm_id.size
485
    assert_equal 1, companies(:first_firm).clients_grouped_by_firm_id.length
486
    assert_equal 2, companies(:first_firm).clients_grouped_by_name.size
487 488 489
    assert_equal 2, companies(:first_firm).clients_grouped_by_name.length
  end

490 491 492 493 494
  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

495
  def test_default_select
496
    assert_equal Comment.column_names.sort, posts(:welcome).comments.first.attributes.keys.sort
497 498 499 500 501 502
  end

  def test_select_query_method
    assert_equal ['id'], posts(:welcome).comments.select(:id).first.attributes.keys
  end

503 504 505 506 507 508 509 510 511 512 513 514
  def test_adding
    force_signal37_to_load_all_clients_of_firm
    natural = Client.new("name" => "Natural Company")
    companies(:first_firm).clients_of_firm << natural
    assert_equal 2, companies(:first_firm).clients_of_firm.size # checking via the collection
    assert_equal 2, companies(:first_firm).clients_of_firm(true).size # checking using the db
    assert_equal natural, companies(:first_firm).clients_of_firm.last
  end

  def test_adding_using_create
    first_firm = companies(:first_firm)
    assert_equal 2, first_firm.plain_clients.size
515
    first_firm.plain_clients.create(:name => "Natural Company")
516 517 518 519 520
    assert_equal 3, first_firm.plain_clients.length
    assert_equal 3, first_firm.plain_clients.size
  end

  def test_create_with_bang_on_has_many_when_parent_is_new_raises
521
    assert_raise(ActiveRecord::RecordNotSaved) do
522 523 524 525 526 527
      firm = Firm.new
      firm.plain_clients.create! :name=>"Whoever"
    end
  end

  def test_regular_create_on_has_many_when_parent_is_new_raises
528
    assert_raise(ActiveRecord::RecordNotSaved) do
529 530 531 532 533 534
      firm = Firm.new
      firm.plain_clients.create :name=>"Whoever"
    end
  end

  def test_create_with_bang_on_has_many_raises_when_record_not_saved
535
    assert_raise(ActiveRecord::RecordInvalid) do
536
      firm = Firm.all.merge!(:order => "id").first
537 538 539 540 541
      firm.plain_clients.create!
    end
  end

  def test_create_with_bang_on_habtm_when_parent_is_new_raises
542
    assert_raise(ActiveRecord::RecordNotSaved) do
543 544 545 546 547
      Developer.new("name" => "Aredridel").projects.create!
    end
  end

  def test_adding_a_mismatch_class
548 549 550
    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) }
551 552 553 554 555 556 557 558 559
  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")])
    assert_equal 3, companies(:first_firm).clients_of_firm.size
    assert_equal 3, companies(:first_firm).clients_of_firm(true).size
  end

560
  def test_transactions_when_adding_to_persisted
J
Jon Leighton 已提交
561 562 563 564 565 566 567 568 569
    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

    assert !companies(:first_firm).clients_of_firm(true).include?(good)
570 571 572
  end

  def test_transactions_when_adding_to_new_record
J
Jon Leighton 已提交
573 574 575 576
    assert_no_queries do
      firm = Firm.new
      firm.clients_of_firm.concat(Client.new("name" => "Natural Company"))
    end
577 578
  end

579 580 581 582 583 584 585 586 587 588
  def test_new_aliased_to_build
    company = companies(:first_firm)
    new_client = assert_no_queries { company.clients_of_firm.new("name" => "Another Client") }
    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

589 590 591 592
  def test_build
    company = companies(:first_firm)
    new_client = assert_no_queries { company.clients_of_firm.build("name" => "Another Client") }
    assert !company.clients_of_firm.loaded?
593

594
    assert_equal "Another Client", new_client.name
595
    assert !new_client.persisted?
596 597 598
    assert_equal new_client, company.clients_of_firm.last
  end

599 600 601 602 603 604 605
  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")
    assert_equal 3, company.clients_of_firm.size
  end

606 607 608 609 610 611 612 613 614 615 616 617
  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

618 619 620 621 622 623 624
  def test_build_many
    company = companies(:first_firm)
    new_clients = assert_no_queries { company.clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}]) }
    assert_equal 2, new_clients.size
  end

  def test_build_followed_by_save_does_not_load_target
625
    companies(:first_firm).clients_of_firm.build("name" => "Another Client")
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
    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

644 645 646 647 648 649
  def test_build_via_block
    company = companies(:first_firm)
    new_client = assert_no_queries { company.clients_of_firm.build {|client| client.name = "Another Client" } }
    assert !company.clients_of_firm.loaded?

    assert_equal "Another Client", new_client.name
650
    assert !new_client.persisted?
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
    assert_equal new_client, company.clients_of_firm.last
  end

  def test_build_many_via_block
    company = companies(:first_firm)
    new_clients = assert_no_queries do
      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

667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
  def test_create_without_loading_association
    first_firm  = companies(:first_firm)
    Firm.column_names
    Client.column_names

    assert_equal 1, first_firm.clients_of_firm.size
    first_firm.clients_of_firm.reset

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

    assert_equal 2, first_firm.clients_of_firm.size
  end

  def test_create
    force_signal37_to_load_all_clients_of_firm
    new_client = companies(:first_firm).clients_of_firm.create("name" => "Another Client")
685
    assert new_client.persisted?
686 687 688 689 690 691 692 693 694 695
    assert_equal new_client, companies(:first_firm).clients_of_firm.last
    assert_equal new_client, companies(:first_firm).clients_of_firm(true).last
  end

  def test_create_many
    companies(:first_firm).clients_of_firm.create([{"name" => "Another Client"}, {"name" => "Another Client II"}])
    assert_equal 3, companies(:first_firm).clients_of_firm(true).size
  end

  def test_create_followed_by_save_does_not_load_target
696
    companies(:first_firm).clients_of_firm.create("name" => "Another Client")
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
    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)
    assert_equal 0, companies(:first_firm).clients_of_firm.size
    assert_equal 0, companies(:first_firm).clients_of_firm(true).size
  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

716
  def test_deleting_updates_counter_cache
J
Jon Leighton 已提交
717
    topic = Topic.order("id ASC").first
718 719 720 721 722 723 724
    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

725
  def test_deleting_updates_counter_cache_without_dependent_option
726 727 728 729 730 731 732
    post = posts(:welcome)

    assert_difference "post.reload.taggings_count", -1 do
      post.taggings.delete(post.taggings.first)
    end
  end

733 734
  def test_deleting_updates_counter_cache_with_dependent_delete_all
    post = posts(:welcome)
735
    post.update_columns(taggings_with_delete_all_count: post.taggings_count)
736 737 738 739 740 741

    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

742 743
  def test_deleting_updates_counter_cache_with_dependent_destroy
    post = posts(:welcome)
744
    post.update_columns(taggings_with_destroy_count: post.taggings_count)
745 746 747 748 749 750

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

751 752 753 754 755 756 757 758
  def test_custom_named_counter_cache
    topic = topics(:first)

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

759 760 761 762 763 764 765 766 767 768 769 770
  def test_deleting_a_collection
    force_signal37_to_load_all_clients_of_firm
    companies(:first_firm).clients_of_firm.create("name" => "Another Client")
    assert_equal 2, 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]])
    assert_equal 0, companies(:first_firm).clients_of_firm.size
    assert_equal 0, companies(:first_firm).clients_of_firm(true).size
  end

  def test_delete_all
    force_signal37_to_load_all_clients_of_firm
    companies(:first_firm).clients_of_firm.create("name" => "Another Client")
771 772 773 774
    clients = companies(:first_firm).clients_of_firm.to_a
    assert_equal 2, clients.count
    deleted = companies(:first_firm).clients_of_firm.delete_all
    assert_equal clients.sort_by(&:id), deleted.sort_by(&:id)
775 776 777 778 779 780 781 782 783 784 785 786 787 788
    assert_equal 0, companies(:first_firm).clients_of_firm.size
    assert_equal 0, companies(:first_firm).clients_of_firm(true).size
  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")
    assert_equal 2, companies(:first_firm).clients_of_firm.size
    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
    assert_equal 0, companies(:first_firm).clients_of_firm(true).size
  end

789
  def test_transaction_when_deleting_persisted
J
Jon Leighton 已提交
790 791 792 793 794 795 796 797 798 799 800
    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

    assert_equal [good, bad], companies(:first_firm).clients_of_firm(true)
801 802 803
  end

  def test_transaction_when_deleting_new_record
J
Jon Leighton 已提交
804 805 806 807 808 809
    assert_no_queries do
      firm = Firm.new
      client = Client.new("name" => "New Client")
      firm.clients_of_firm << client
      firm.clients_of_firm.destroy(client)
    end
810 811
  end

812 813 814 815 816
  def test_clearing_an_association_collection
    firm = companies(:first_firm)
    client_id = firm.clients_of_firm.first.id
    assert_equal 1, firm.clients_of_firm.size

J
Jon Leighton 已提交
817
    firm.clients_of_firm.clear
818 819 820 821 822 823 824

    assert_equal 0, firm.clients_of_firm.size
    assert_equal 0, firm.clients_of_firm(true).size
    assert_equal [], Client.destroyed_client_ids[firm.id]

    # Should not be destroyed since the association is not dependent.
    assert_nothing_raised do
825
      assert_nil Client.find(client_id).firm
826 827 828
    end
  end

829 830 831
  def test_clearing_updates_counter_cache
    topic = Topic.first

832 833 834
    assert_difference 'topic.reload.replies_count', -1 do
      topic.replies.clear
    end
835 836
  end

837 838 839 840 841 842 843 844 845
  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

846 847 848 849 850 851 852 853 854 855 856 857 858
  def test_clearing_a_dependent_association_collection
    firm = companies(:first_firm)
    client_id = firm.dependent_clients_of_firm.first.id
    assert_equal 1, firm.dependent_clients_of_firm.size

    # :dependent means destroy is called on each client
    firm.dependent_clients_of_firm.clear

    assert_equal 0, firm.dependent_clients_of_firm.size
    assert_equal 0, firm.dependent_clients_of_firm(true).size
    assert_equal [client_id], Client.destroyed_client_ids[firm.id]

    # Should be destroyed since the association is dependent.
859
    assert_nil Client.find_by_id(client_id)
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
  end

  def test_clearing_an_exclusively_dependent_association_collection
    firm = companies(:first_firm)
    client_id = firm.exclusively_dependent_clients_of_firm.first.id
    assert_equal 1, firm.exclusively_dependent_clients_of_firm.size

    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
    assert_equal 0, firm.exclusively_dependent_clients_of_firm(true).size
    # no destroy-filters should have been called
    assert_equal [], Client.destroyed_client_ids[firm.id]

    # Should be destroyed since the association is exclusively dependent.
879
    assert_nil Client.find_by_id(client_id)
880 881 882 883 884 885 886
  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 已提交
887
    assert_equal 2, Client.where(client_of: firm.id).size
888 889 890
    assert_equal 1, firm.dependent_conditional_clients_of_firm.size
    firm.destroy
    # only the correctly associated client should have been deleted
J
Jon Leighton 已提交
891
    assert_equal 1, Client.where(client_of: firm.id).size
892 893 894 895 896 897 898
  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 已提交
899
    assert_equal 2, Client.where(client_of: firm.id).size
900 901 902
    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 已提交
903
    assert_equal 1, Client.where(client_of: firm.id).size
904 905
  end

906 907 908 909 910
  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 已提交
911
    assert_equal 2, Client.where(client_of: firm.id).size
912 913 914
    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 已提交
915
    assert_equal 1, Client.where(client_of: firm.id).size
916 917
  end

918
  def test_delete_all_association_with_primary_key_deletes_correct_records
919
    firm = Firm.first
920 921
    # break the vanilla firm_id foreign key
    assert_equal 2, firm.clients.count
922
    firm.clients.first.update_columns(firm_id: nil)
923 924 925
    assert_equal 1, firm.clients(true).count
    assert_equal 1, firm.clients_using_primary_key_with_delete_all.count
    old_record = firm.clients_using_primary_key_with_delete_all.first
926
    firm = Firm.first
927
    firm.destroy
928
    assert_nil Client.find_by_id(old_record.id)
929
  end
930

931 932
  def test_creation_respects_hash_condition
    ms_client = companies(:first_firm).clients_like_ms_with_hash_conditions.build
933

934 935
    assert        ms_client.save
    assert_equal  'Microsoft', ms_client.name
936

937 938
    another_ms_client = companies(:first_firm).clients_like_ms_with_hash_conditions.create

939
    assert        another_ms_client.persisted?
940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
    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
    assert_equal 0, firm.clients_of_firm(true).size
  end

  def test_deleting_a_item_which_is_not_in_the_collection
    force_signal37_to_load_all_clients_of_firm
    summit = Client.find_by_name('Summit')
    companies(:first_firm).clients_of_firm.delete(summit)
    assert_equal 1, companies(:first_firm).clients_of_firm.size
    assert_equal 1, companies(:first_firm).clients_of_firm(true).size
    assert_equal 2, summit.client_of
  end

961
  def test_deleting_by_fixnum_id
962
    david = Developer.find(1)
963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978

    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
979 980 981 982 983
  end

  def test_deleting_self_type_mismatch
    david = Developer.find(1)
    david.projects.reload
984
    assert_raise(ActiveRecord::AssociationTypeMismatch) { david.projects.delete(Project.find(1).developers) }
985 986
  end

987 988 989 990 991 992 993 994 995 996 997
  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

    assert_equal 0, companies(:first_firm).reload.clients_of_firm.size
    assert_equal 0, companies(:first_firm).clients_of_firm(true).size
  end

998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
  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

    assert_equal 0, companies(:first_firm).reload.clients_of_firm.size
    assert_equal 0, companies(:first_firm).clients_of_firm(true).size
  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

    assert_equal 0, companies(:first_firm).reload.clients_of_firm.size
    assert_equal 0, companies(:first_firm).clients_of_firm(true).size
  end

1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
  def test_destroying_a_collection
    force_signal37_to_load_all_clients_of_firm
    companies(:first_firm).clients_of_firm.create("name" => "Another Client")
    assert_equal 2, companies(:first_firm).clients_of_firm.size

    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

    assert_equal 0, companies(:first_firm).reload.clients_of_firm.size
    assert_equal 0, companies(:first_firm).clients_of_firm(true).size
  end

1033 1034
  def test_destroy_all
    force_signal37_to_load_all_clients_of_firm
1035 1036 1037 1038 1039
    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)
    assert destroyed.all? { |client| client.frozen? }, "destroyed clients should be frozen"
1040 1041 1042 1043 1044 1045 1046 1047
    assert companies(:first_firm).clients_of_firm.empty?, "37signals has no clients after destroy all"
    assert companies(:first_firm).clients_of_firm(true).empty?, "37signals has no clients after destroy all and refresh"
  end

  def test_dependence
    firm = companies(:first_firm)
    assert_equal 2, firm.clients.size
    firm.destroy
1048
    assert Client.all.merge!(:where => "firm_id=#{firm.id}").to_a.empty?
1049 1050
  end

1051 1052 1053 1054 1055
  def test_dependence_for_associations_with_hash_condition
    david = authors(:david)
    assert_difference('Post.count', -1) { assert david.destroy }
  end

1056
  def test_destroy_dependent_when_deleted_from_association
1057
    # sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first
1058
    firm = Firm.all.merge!(:order => "id").first
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
    assert_equal 2, firm.clients.size

    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) }
    assert_equal 1, firm.clients.size
  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"
1072
    reply.replies.create "title" => "neat and simple", "content" => "ain't complaining"
1073 1074 1075 1076 1077 1078 1079 1080 1081

    assert_nothing_raised { topic.destroy }
  end

  uses_transaction :test_dependence_with_transaction_support_on_failure
  def test_dependence_with_transaction_support_on_failure
    firm = companies(:first_firm)
    clients = firm.clients
    assert_equal 2, clients.length
1082
    clients.last.instance_eval { def overwrite_to_raise() raise "Trigger rollback" end }
1083 1084 1085

    firm.destroy rescue "do nothing"

1086
    assert_equal 2, Client.all.merge!(:where => "firm_id=#{firm.id}").to_a.size
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
  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

1109
  def test_restrict
1110
    firm = RestrictedFirm.create!(:name => 'restrict')
1111
    firm.companies.create(:name => 'child')
1112

1113 1114
    assert !firm.companies.empty?
    assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
1115 1116 1117 1118
    assert RestrictedFirm.exists?(:name => 'restrict')
    assert firm.companies.exists?(:name => 'child')
  end

1119 1120 1121 1122
  def test_restrict_is_deprecated
    klass = Class.new(ActiveRecord::Base)
    assert_deprecated { klass.has_many :posts, dependent: :restrict }
  end
1123

1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
  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

  def test_restrict_with_error
    firm = RestrictedWithErrorFirm.create!(:name => 'restrict')
1136 1137 1138 1139 1140 1141 1142 1143
    firm.companies.create(:name => 'child')

    assert !firm.companies.empty?

    firm.destroy

    assert !firm.errors.empty?

1144
    assert_equal "Cannot delete record because dependent companies exist", firm.errors[:base].first
1145
    assert RestrictedWithErrorFirm.exists?(:name => 'restrict')
1146
    assert firm.companies.exists?(:name => 'child')
1147 1148
  end

1149 1150 1151 1152
  def test_included_in_collection
    assert companies(:first_firm).clients.include?(Client.find(2))
  end

1153 1154 1155 1156 1157 1158 1159
  def test_included_in_collection_for_new_records
    client = Client.create(:name => 'Persisted')
    assert_nil client.client_of
    assert !Firm.new.clients_of_firm.include?(client),
           'includes a client that does not belong to any firm'
  end

1160
  def test_adding_array_and_collection
J
Jon Leighton 已提交
1161
    assert_nothing_raised { Firm.first.clients + Firm.all.last.clients }
1162 1163 1164
  end

  def test_replace_with_less
1165
    firm = Firm.all.merge!(:order => "id").first
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
    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
1179
    firm = Firm.all.merge!(:order => "id").first
1180 1181 1182 1183 1184 1185 1186
    firm.clients = [companies(:second_client), Client.new("name" => "New Client")]
    firm.save
    firm.reload
    assert_equal 2, firm.clients.length
    assert !firm.clients.include?(:first_client)
  end

1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
  def test_replace_failure
    firm = companies(:first_firm)
    account = Account.new
    orig_accounts = firm.accounts.to_a

    assert !account.valid?
    assert !orig_accounts.empty?
    assert_raise ActiveRecord::RecordNotSaved do
      firm.accounts = [account]
    end
    assert_equal orig_accounts, firm.accounts
  end

1200
  def test_transactions_when_replacing_on_persisted
J
Jon Leighton 已提交
1201 1202
    good = Client.new(:name => "Good")
    bad  = Client.new(:name => "Bad", :raise_on_save => true)
1203

J
Jon Leighton 已提交
1204 1205 1206 1207 1208 1209 1210 1211
    companies(:first_firm).clients_of_firm = [good]

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

    assert_equal [good], companies(:first_firm).clients_of_firm(true)
1212 1213 1214
  end

  def test_transactions_when_replacing_on_new_record
J
Jon Leighton 已提交
1215 1216 1217 1218
    assert_no_queries do
      firm = Firm.new
      firm.clients_of_firm = [Client.new("name" => "New Client")]
    end
1219 1220
  end

1221 1222 1223 1224
  def test_get_ids
    assert_equal [companies(:first_client).id, companies(:second_client).id], companies(:first_firm).client_ids
  end

1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
  def test_get_ids_for_loaded_associations
    company = companies(:first_firm)
    company.clients(true)
    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?
    assert_equal [companies(:first_client).id, companies(:second_client).id], company.client_ids
    assert !company.clients.loaded?
  end

1241 1242 1243 1244
  def test_get_ids_ignores_include_option
    assert_equal [readers(:michael_welcome).id], posts(:welcome).readers_with_person_ids
  end

1245 1246 1247 1248 1249 1250 1251
  def test_get_ids_for_unloaded_finder_sql_associations_loads_them
    company = companies(:first_firm)
    assert !company.clients_using_sql.loaded?
    assert_equal [companies(:second_client).id], company.clients_using_sql_ids
    assert company.clients_using_sql.loaded?
  end

1252
  def test_get_ids_for_ordered_association
1253
    assert_equal [companies(:second_client).id, companies(:first_client).id], companies(:first_firm).clients_ordered_by_name_ids
1254 1255
  end

1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
  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!

    assert_equal 2, firm.clients(true).size
    assert firm.clients.include?(companies(:second_client))
  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) },
1275
    ].each {|block| assert_raise(ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection, &block) }
1276 1277 1278
  end

  def test_dynamic_find_should_respect_association_order_for_through
1279
    assert_equal Comment.find(10), authors(:david).comments_desc.where("comments.type = 'SpecialComment'").first
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
    assert_equal Comment.find(10), authors(:david).comments_desc.find_by_type('SpecialComment')
  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 已提交
1290
    firm.clients.load_target
1291

1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
    client = firm.clients.first

    assert_no_queries do
      assert firm.clients.loaded?
      assert firm.clients.include?(client)
    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
      assert firm.clients.include?(client)
    end
    assert ! firm.clients.loaded?
  end

1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
  def test_include_loads_collection_if_target_uses_finder_sql
    firm = companies(:first_firm)
    client = firm.clients_using_sql.first

    firm.reload
    assert ! firm.clients_using_sql.loaded?
    assert firm.clients_using_sql.include?(client)
    assert firm.clients_using_sql.loaded?
  end


1323 1324 1325 1326 1327 1328 1329 1330
  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?
    assert ! firm.clients.include?(client)
  end

1331 1332 1333 1334 1335 1336 1337 1338 1339
  def test_calling_first_or_last_on_association_should_not_load_association
    firm = companies(:first_firm)
    firm.clients.first
    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 已提交
1340
    firm.clients.load_target
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
    assert firm.clients.loaded?

    assert_no_queries do
      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
      firm.clients.last
    end

    assert firm.clients.loaded?
  end

1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
  def test_calling_first_or_last_on_existing_record_with_create_should_not_load_association
    firm = companies(:first_firm)
    firm.clients.create(:name => 'Foo')
    assert !firm.clients.loaded?

    assert_queries 2 do
      firm.clients.first
      firm.clients.last
    end

    assert !firm.clients.loaded?
  end

1377 1378 1379 1380 1381 1382 1383 1384
  def test_calling_first_or_last_on_new_record_should_not_run_queries
    firm = Firm.new

    assert_no_queries do
      firm.clients.first
      firm.clients.last
    end
  end
1385

1386 1387 1388
  def test_custom_primary_key_on_new_record_should_fetch_with_query
    author = Author.new(:name => "David")
    assert !author.essays.loaded?
1389 1390

    assert_queries 1 do
1391 1392
      assert_equal 1, author.essays.size
    end
1393

J
Jon Leighton 已提交
1394
    assert_equal author.essays, Essay.where(writer_id: "David")
1395
  end
1396

1397 1398
  def test_has_many_custom_primary_key
    david = authors(:david)
J
Jon Leighton 已提交
1399
    assert_equal david.essays, Essay.where(writer_id: "David")
1400
  end
1401

1402 1403 1404
  def test_blank_custom_primary_key_on_new_record_should_not_run_queries
    author = Author.new
    assert !author.essays.loaded?
1405 1406

    assert_queries 0 do
1407 1408 1409
      assert_equal 0, author.essays.size
    end
  end
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421

  def test_calling_first_or_last_with_integer_on_association_should_load_association
    firm = companies(:first_firm)

    assert_queries 1 do
      firm.clients.first(2)
      firm.clients.last(2)
    end

    assert firm.clients.loaded?
  end

1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
  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?
    assert_equal 2, firm.clients.size
  end

1461 1462 1463 1464 1465 1466 1467
  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' })

1468
    stats = Namespaced::Firm.all.merge!(
1469
      :select => "#{Namespaced::Firm.table_name}.id, COUNT(#{Namespaced::Client.table_name}.id) AS num_clients",
1470 1471
      :joins  => :clients,
      :group  => "#{Namespaced::Firm.table_name}.id"
J
Jon Leighton 已提交
1472
    ).find firm.id
1473 1474 1475 1476 1477
    assert_equal 1, stats.num_clients.to_i
  ensure
    ActiveRecord::Base.store_full_sti_class = old
  end

1478 1479
  def test_association_proxy_transaction_method_starts_transaction_in_association_class
    Comment.expects(:transaction)
1480
    Post.first.comments.transaction do
1481
      # nothing
1482 1483 1484
    end
  end

1485
  def test_sending_new_to_association_proxy_should_have_same_effect_as_calling_new
1486 1487 1488 1489 1490 1491 1492 1493
    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)
1494
  end
1495 1496

  def test_creating_using_primary_key
1497
    firm = Firm.all.merge!(:order => "id").first
1498 1499 1500
    client = firm.clients_using_primary_key.create!(:name => 'test')
    assert_equal firm.name, client.firm_name
  end
1501 1502 1503

  def test_defining_has_many_association_with_delete_all_dependency_lazily_evaluates_target_class
    ActiveRecord::Reflection::AssociationReflection.any_instance.expects(:class_name).never
1504
    class_eval(<<-EOF, __FILE__, __LINE__ + 1)
1505 1506 1507 1508 1509 1510 1511 1512
      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
1513
    class_eval(<<-EOF, __FILE__, __LINE__ + 1)
1514 1515 1516 1517 1518
      class NullifyModel < ActiveRecord::Base
        has_many :nonentities, :dependent => :nullify
      end
    EOF
  end
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530

  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
1531 1532 1533 1534 1535 1536

  def test_include_method_in_has_many_association_should_return_true_for_instance_added_with_build
    post = Post.new
    comment = post.comments.build
    assert post.comments.include?(comment)
  end
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557

  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
1558 1559 1560 1561 1562 1563 1564

  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
1565 1566 1567 1568 1569 1570 1571 1572 1573 1574

  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
1575

1576 1577 1578 1579 1580
  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 已提交
1581 1582 1583 1584 1585 1586 1587 1588

  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
1589 1590 1591 1592 1593 1594 1595

  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
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606

  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
1607

1608
  def test_replace_returns_target
1609 1610 1611 1612 1613 1614
    car = Car.create(:name => 'honda')
    bulb1 = car.bulbs.create
    bulb2 = car.bulbs.create
    bulb3 = Bulb.create

    assert_equal [bulb1, bulb2], car.bulbs
1615
    result = car.bulbs.replace([bulb3, bulb1])
1616 1617 1618 1619
    assert_equal [bulb1, bulb3], car.bulbs
    assert_equal [bulb1, bulb3], result
  end

1620 1621 1622 1623
  def test_collection_association_with_private_kernel_method
    firm = companies(:first_firm)
    assert_equal [accounts(:signals37)], firm.accounts.open
  end
J
Jon Leighton 已提交
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637

  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
1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649

  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
1650 1651 1652 1653 1654 1655 1656 1657 1658 1659

  test ":finder_sql is deprecated" do
    klass = Class.new(ActiveRecord::Base)
    assert_deprecated { klass.has_many :foo, :finder_sql => 'lol' }
  end

  test ":counter_sql is deprecated" do
    klass = Class.new(ActiveRecord::Base)
    assert_deprecated { klass.has_many :foo, :counter_sql => 'lol' }
  end
1660 1661 1662 1663 1664 1665 1666

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

    assert_no_queries do
      assert_equal [], post.comments
      assert_equal [], post.comments.where(body: 'omg')
1667
      assert_equal [], post.comments.pluck(:body)
1668
      assert_equal 0,  post.comments.sum(:id)
V
Vipul A M 已提交
1669
      assert_equal 0,  post.comments.count
1670 1671
    end
  end
1672
end