associations_test.rb 60.2 KB
Newer Older
D
Initial  
David Heinemeier Hansson 已提交
1 2 3 4 5 6
require 'abstract_unit'
require 'fixtures/developer'
require 'fixtures/project'
require 'fixtures/company'
require 'fixtures/topic'
require 'fixtures/reply'
7
require 'fixtures/computer'
8 9
require 'fixtures/customer'
require 'fixtures/order'
10
require 'fixtures/category'
11 12
require 'fixtures/post'
require 'fixtures/author'
D
Initial  
David Heinemeier Hansson 已提交
13 14 15


class AssociationsTest < Test::Unit::TestCase
16 17
  fixtures :accounts, :companies, :developers, :projects, :developers_projects,
           :computers
18

J
Jeremy Kemper 已提交
19 20 21 22 23 24
  def test_bad_collection_keys
    assert_raise(ArgumentError, 'ActiveRecord should have barked on bad collection keys') do
      Class.new(ActiveRecord::Base).has_many(:wheels, :name => 'wheels')
    end
  end

D
Initial  
David Heinemeier Hansson 已提交
25
  def test_force_reload
26
    firm = Firm.new("name" => "A New Firm, Inc")
D
Initial  
David Heinemeier Hansson 已提交
27 28 29
    firm.save
    firm.clients.each {|c|} # forcing to load all clients
    assert firm.clients.empty?, "New firm shouldn't have client objects"
30 31 32
    assert_deprecated do
      assert !firm.has_clients?, "New firm shouldn't have clients"
    end
D
Initial  
David Heinemeier Hansson 已提交
33 34
    assert_equal 0, firm.clients.size, "New firm should have 0 clients"

35
    client = Client.new("name" => "TheClient.com", "firm_id" => firm.id)
D
Initial  
David Heinemeier Hansson 已提交
36 37 38
    client.save

    assert firm.clients.empty?, "New firm should have cached no client objects"
39 40 41
    assert_deprecated do
      assert !firm.has_clients?, "New firm should have cached a no-clients response"
    end
D
Initial  
David Heinemeier Hansson 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
    assert_equal 0, firm.clients.size, "New firm should have cached 0 clients count"

    assert !firm.clients(true).empty?, "New firm should have reloaded client objects"
    assert_equal 1, firm.clients(true).size, "New firm should have reloaded clients count"
  end

  def test_storing_in_pstore
    require "tmpdir"
    store_filename = File.join(Dir.tmpdir, "ar-pstore-association-test")
    File.delete(store_filename) if File.exists?(store_filename)
    require "pstore"
    apple = Firm.create("name" => "Apple")
    natural = Client.new("name" => "Natural Company")
    apple.clients << natural

    db = PStore.new(store_filename)
    db.transaction do
      db["apple"] = apple
    end

    db = PStore.new(store_filename)
    db.transaction do
      assert_equal "Natural Company", db["apple"].clients.first.name
    end
  end
end

69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
class AssociationProxyTest < Test::Unit::TestCase
  fixtures :authors, :posts
  
  def test_proxy_accessors
    welcome = posts(:welcome)
    assert_equal  welcome, welcome.author.proxy_owner
    assert_equal  welcome.class.reflect_on_association(:author), welcome.author.proxy_reflection
    welcome.author.class  # force load target
    assert_equal  welcome.author, welcome.author.proxy_target

    david = authors(:david)
    assert_equal  david, david.posts.proxy_owner
    assert_equal  david.class.reflect_on_association(:posts), david.posts.proxy_reflection
    david.posts.first   # force load target
    assert_equal  david.posts, david.posts.proxy_target
    
    assert_equal  david, david.posts_with_extension.testing_proxy_owner
    assert_equal  david.class.reflect_on_association(:posts_with_extension), david.posts_with_extension.testing_proxy_reflection
    david.posts_with_extension.first   # force load target
    assert_equal  david.posts_with_extension, david.posts_with_extension.testing_proxy_target
  end
end

D
Initial  
David Heinemeier Hansson 已提交
92
class HasOneAssociationsTest < Test::Unit::TestCase
93
  fixtures :accounts, :companies, :developers, :projects, :developers_projects
D
Initial  
David Heinemeier Hansson 已提交
94
  
95 96 97 98
  def setup
    Account.destroyed_account_ids.clear
  end
  
D
Initial  
David Heinemeier Hansson 已提交
99
  def test_has_one
100 101
    assert_equal companies(:first_firm).account, Account.find(1)
    assert_equal Account.find(1).credit_limit, companies(:first_firm).account.credit_limit
D
Initial  
David Heinemeier Hansson 已提交
102 103
  end

104
  def test_has_one_cache_nils
105 106 107
    firm = companies(:another_firm)
    assert_queries(1) { assert_nil firm.account }
    assert_queries(0) { assert_nil firm.account }
108 109 110

    firms = Firm.find(:all, :include => :account)
    assert_queries(0) { firms.each(&:account) }
111 112
  end

113 114 115 116 117 118 119 120 121 122 123 124
  def test_can_marshal_has_one_association_with_nil_target
    firm = Firm.new
    assert_nothing_raised do
      assert_equal firm.attributes, Marshal.load(Marshal.dump(firm)).attributes
    end

    firm.account
    assert_nothing_raised do
      assert_equal firm.attributes, Marshal.load(Marshal.dump(firm)).attributes
    end
  end

125 126 127 128 129
  def test_proxy_assignment
    company = companies(:first_firm)
    assert_nothing_raised { company.account = company.account }
  end

130
  def test_triple_equality
131
    assert Account === companies(:first_firm).account
132
    assert companies(:first_firm).account === Account
133 134
  end

D
Initial  
David Heinemeier Hansson 已提交
135
  def test_type_mismatch
136 137
    assert_raises(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).account = 1 }
    assert_raises(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).account = Project.find(1) }
D
Initial  
David Heinemeier Hansson 已提交
138 139 140 141 142 143 144 145 146 147
  end

  def test_natural_assignment
    apple = Firm.create("name" => "Apple")
    citibank = Account.create("credit_limit" => 10)
    apple.account = citibank
    assert_equal apple.id, citibank.firm_id
  end
  
  def test_natural_assignment_to_nil
148 149 150 151
    old_account_id = companies(:first_firm).account.id
    companies(:first_firm).account = nil
    companies(:first_firm).save
    assert_nil companies(:first_firm).account
152 153
    # account is dependent, therefore is destroyed when reference to owner is lost
    assert_raises(ActiveRecord::RecordNotFound) { Account.find(old_account_id) } 
D
Initial  
David Heinemeier Hansson 已提交
154
  end
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
  
  def test_assignment_without_replacement
    apple = Firm.create("name" => "Apple")
    citibank = Account.create("credit_limit" => 10)
    apple.account = citibank
    assert_equal apple.id, citibank.firm_id
    
    hsbc = apple.build_account({ :credit_limit => 20}, false)
    assert_equal apple.id, hsbc.firm_id
    hsbc.save
    assert_equal apple.id, citibank.firm_id

    nykredit = apple.create_account({ :credit_limit => 30}, false)
    assert_equal apple.id, nykredit.firm_id
    assert_equal apple.id, citibank.firm_id
    assert_equal apple.id, hsbc.firm_id
  end

  def test_assignment_without_replacement_on_create
    apple = Firm.create("name" => "Apple")
    citibank = Account.create("credit_limit" => 10)
    apple.account = citibank
    assert_equal apple.id, citibank.firm_id
    
179
    hsbc = apple.create_account({:credit_limit => 10}, false)
180 181 182 183
    assert_equal apple.id, hsbc.firm_id
    hsbc.save
    assert_equal apple.id, citibank.firm_id
  end
D
Initial  
David Heinemeier Hansson 已提交
184

185
  def test_dependence
186
    num_accounts = Account.count
187 188
    firm = Firm.find(1)
    assert !firm.account.nil?
189 190
    account_id = firm.account.id
    assert_equal [], Account.destroyed_account_ids[firm.id]
191 192
    firm.destroy                
    assert_equal num_accounts - 1, Account.count
193 194
    assert_equal [account_id], Account.destroyed_account_ids[firm.id]
  end
195

196 197 198 199 200
  def test_deprecated_exclusive_dependence
    assert_deprecated(/:exclusively_dependent.*:dependent => :delete_all/) do
      Firm.has_many :deprecated_exclusively_dependent_clients, :class_name => 'Client', :exclusively_dependent => true
    end
  end
201

202 203 204 205 206 207 208 209 210
  def test_exclusive_dependence
    num_accounts = Account.count
    firm = ExclusivelyDependentFirm.find(9)
    assert !firm.account.nil?
    account_id = firm.account.id
    assert_equal [], Account.destroyed_account_ids[firm.id]
    firm.destroy
    assert_equal num_accounts - 1, Account.count
    assert_equal [], Account.destroyed_account_ids[firm.id]
211 212
  end

213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
  def test_succesful_build_association
    firm = Firm.new("name" => "GlobalMegaCorp")
    firm.save

    account = firm.build_account("credit_limit" => 1000)
    assert account.save
    assert_equal account, firm.account
  end

  def test_failing_build_association
    firm = Firm.new("name" => "GlobalMegaCorp")
    firm.save

    account = firm.build_account
    assert !account.save
    assert_equal "can't be empty", account.errors.on("credit_limit")
  end

231 232 233 234 235 236 237 238 239
  def test_build_association_twice_without_saving_affects_nothing
    count_of_account = Account.count
    firm = Firm.find(:first)
    account1 = firm.build_account("credit_limit" => 1000)
    account2 = firm.build_account("credit_limit" => 2000)

    assert_equal count_of_account, Account.count
  end

240 241 242 243 244 245
  def test_create_association
    firm = Firm.new("name" => "GlobalMegaCorp")
    firm.save
    assert_equal firm.create_account("credit_limit" => 1000), firm.account
  end

D
Initial  
David Heinemeier Hansson 已提交
246 247 248
  def test_build
    firm = Firm.new("name" => "GlobalMegaCorp")
    firm.save
249

250
    firm.account = account = Account.new("credit_limit" => 1000)
251
    assert_equal account, firm.account
D
Initial  
David Heinemeier Hansson 已提交
252 253 254 255
    assert account.save
    assert_equal account, firm.account
  end

256 257 258 259 260
  def test_build_before_child_saved
    firm = Firm.find(1)

    account = firm.account.build("credit_limit" => 1000)
    assert_equal account, firm.account
261
    assert account.new_record?
262 263
    assert firm.save
    assert_equal account, firm.account
264
    assert !account.new_record?
265 266 267 268 269
  end

  def test_build_before_either_saved
    firm = Firm.new("name" => "GlobalMegaCorp")

270
    firm.account = account = Account.new("credit_limit" => 1000)
271
    assert_equal account, firm.account
272
    assert account.new_record?
273 274
    assert firm.save
    assert_equal account, firm.account
275
    assert !account.new_record?
276 277
  end

D
Initial  
David Heinemeier Hansson 已提交
278 279 280 281
  def test_failing_build_association
    firm = Firm.new("name" => "GlobalMegaCorp")
    firm.save
    
282
    firm.account = account = Account.new
283
    assert_equal account, firm.account
D
Initial  
David Heinemeier Hansson 已提交
284
    assert !account.save
285
    assert_equal account, firm.account
D
Initial  
David Heinemeier Hansson 已提交
286 287 288 289 290 291
    assert_equal "can't be empty", account.errors.on("credit_limit")
  end

  def test_create
    firm = Firm.new("name" => "GlobalMegaCorp")
    firm.save
292 293
    firm.account = account = Account.create("credit_limit" => 1000)
    assert_equal account, firm.account
D
Initial  
David Heinemeier Hansson 已提交
294
  end
295 296 297

  def test_create_before_save
    firm = Firm.new("name" => "GlobalMegaCorp")
298 299
    firm.account = account = Account.create("credit_limit" => 1000)
    assert_equal account, firm.account
D
Initial  
David Heinemeier Hansson 已提交
300 301 302 303
  end

  def test_dependence_with_missing_association
    Account.destroy_all
304 305
    firm = Firm.find(1)
    assert firm.account.nil?
D
Initial  
David Heinemeier Hansson 已提交
306 307
    firm.destroy
  end
308 309 310 311

  def test_assignment_before_parent_saved
    firm = Firm.new("name" => "GlobalMegaCorp")
    firm.account = a = Account.find(1)
312
    assert firm.new_record?
313 314 315 316 317
    assert_equal a, firm.account
    assert firm.save
    assert_equal a, firm.account
    assert_equal a, firm.account(true)
  end
318

319 320 321 322 323 324 325
  def test_finding_with_interpolated_condition
    firm = Firm.find(:first)
    superior = firm.clients.create(:name => 'SuperiorCo')
    superior.rating = 10
    superior.save
    assert_equal 10, firm.clients_with_interpolated_conditions.first.rating
  end
326 327 328 329

  def test_assignment_before_child_saved
    firm = Firm.find(1)
    firm.account = a = Account.new("credit_limit" => 1000)
330
    assert !a.new_record?
331 332 333 334 335 336 337 338
    assert_equal a, firm.account
    assert_equal a, firm.account
    assert_equal a, firm.account(true)
  end

  def test_assignment_before_either_saved
    firm = Firm.new("name" => "GlobalMegaCorp")
    firm.account = a = Account.new("credit_limit" => 1000)
339 340
    assert firm.new_record?
    assert a.new_record?
341 342
    assert_equal a, firm.account
    assert firm.save
343 344
    assert !firm.new_record?
    assert !a.new_record?
345 346 347
    assert_equal a, firm.account
    assert_equal a, firm.account(true)
  end
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364

  def test_not_resaved_when_unchanged
    firm = Firm.find(:first, :include => :account)
    assert_queries(1) { firm.save! }

    firm = Firm.find(:first)
    firm.account = Account.find(:first)
    assert_queries(1) { firm.save! }

    firm = Firm.find(:first).clone
    firm.account = Account.find(:first)
    assert_queries(2) { firm.save! }

    firm = Firm.find(:first).clone
    firm.account = Account.find(:first).clone
    assert_queries(2) { firm.save! }
  end
365 366 367 368 369 370 371 372 373 374
  
  def test_save_still_works_after_accessing_nil_has_one
    jp = Company.new :name => 'Jaded Pixel'
    jp.dummy_account.nil?
    
    assert_nothing_raised do
      jp.save!
    end    
  end
  
375 376 377 378 379 380 381
  def test_deprecated_inferred_foreign_key
    assert_not_deprecated { Company.belongs_to :firm }
    assert_not_deprecated { Company.belongs_to :client, :foreign_key => "firm_id" }
    assert_not_deprecated { Company.belongs_to :firm, :class_name => "Firm", :foreign_key => "client_of" }
    assert_deprecated("inferred foreign_key name") { Company.belongs_to :client, :class_name => "Firm" }
  end

D
Initial  
David Heinemeier Hansson 已提交
382 383 384 385
end


class HasManyAssociationsTest < Test::Unit::TestCase
386 387
  fixtures :accounts, :companies, :developers, :projects,
           :developers_projects, :topics
388 389 390 391 392

  def setup
    Client.destroyed_client_ids.clear
  end

D
Initial  
David Heinemeier Hansson 已提交
393
  def force_signal37_to_load_all_clients_of_firm
394
    companies(:first_firm).clients_of_firm.each {|f| }
D
Initial  
David Heinemeier Hansson 已提交
395
  end
396

397
  def test_counting_with_counter_sql
398
    assert_equal 2, Firm.find(:first).clients.count
399
  end
400 401 402 403 404 405

  def test_counting
    assert_equal 2, Firm.find(:first).plain_clients.count
  end

  def test_counting_with_single_conditions
406 407 408
    assert_deprecated 'count' do
      assert_equal 2, Firm.find(:first).plain_clients.count('1=1')
    end
409 410 411 412 413 414 415 416 417 418
  end

  def test_counting_with_single_hash
    assert_equal 2, Firm.find(:first).plain_clients.count(:conditions => '1=1')
  end

  def test_counting_with_column_name_and_hash
    assert_equal 2, Firm.find(:first).plain_clients.count(:all, :conditions => '1=1')
  end

D
Initial  
David Heinemeier Hansson 已提交
419
  def test_finding
420
    assert_equal 2, Firm.find(:first).clients.length
D
Initial  
David Heinemeier Hansson 已提交
421 422
  end

423 424 425 426 427 428
  def test_find_many_with_merged_options
    assert_equal 1, companies(:first_firm).limited_clients.size
    assert_equal 1, companies(:first_firm).limited_clients.find(:all).size
    assert_equal 2, companies(:first_firm).limited_clients.find(:all, :limit => nil).size
  end

429 430 431 432 433
  def test_triple_equality
    assert !(Array === Firm.find(:first).clients)
    assert Firm.find(:first).clients === Array
  end

D
Initial  
David Heinemeier Hansson 已提交
434
  def test_finding_default_orders
435
    assert_equal "Summit", Firm.find(:first).clients.first.name
D
Initial  
David Heinemeier Hansson 已提交
436 437 438
  end

  def test_finding_with_different_class_name_and_order
439
    assert_equal "Microsoft", Firm.find(:first).clients_sorted_desc.first.name
D
Initial  
David Heinemeier Hansson 已提交
440 441 442
  end

  def test_finding_with_foreign_key
443
    assert_equal "Microsoft", Firm.find(:first).clients_of_firm.first.name
D
Initial  
David Heinemeier Hansson 已提交
444 445 446
  end

  def test_finding_with_condition
447
    assert_equal "Microsoft", Firm.find(:first).clients_like_ms.first.name
D
Initial  
David Heinemeier Hansson 已提交
448 449
  end

450 451 452 453
  def test_finding_with_condition_hash
    assert_equal "Microsoft", Firm.find(:first).clients_like_ms_with_hash_conditions.first.name
  end

D
Initial  
David Heinemeier Hansson 已提交
454
  def test_finding_using_sql
455
    firm = Firm.find(:first)
D
Initial  
David Heinemeier Hansson 已提交
456 457 458 459
    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
460
    assert_equal 1, Firm.find(:first).clients_using_sql.size
D
Initial  
David Heinemeier Hansson 已提交
461 462
  end

463
  def test_counting_using_sql
464 465
    assert_equal 1, Firm.find(:first).clients_using_counter_sql.size
    assert_equal 0, Firm.find(:first).clients_using_zero_counter_sql.size
466
  end
467 468

  def test_counting_non_existant_items_using_sql
469
    assert_equal 0, Firm.find(:first).no_clients_using_counter_sql.size
470
  end
471 472 473 474 475 476 477 478 479 480 481 482 483 484
  
  def test_belongs_to_sanity
    c = Client.new
    assert_nil c.firm

    if c.firm
      assert false, "belongs_to failed if check"
    end

    unless c.firm
    else
      assert false,  "belongs_to failed unless check"
    end
  end
485

486
  def test_find_ids
487
    firm = Firm.find(:first)
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505

    assert_raises(ActiveRecord::RecordNotFound) { firm.clients.find }

    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

    assert_raises(ActiveRecord::RecordNotFound) { firm.clients.find(2, 99) }
  end

D
Initial  
David Heinemeier Hansson 已提交
506
  def test_find_all
507 508 509 510 511 512
    assert_deprecated 'find_all' do
      firm = Firm.find_first
      assert_equal firm.clients, firm.clients.find_all
      assert_equal 2, firm.clients.find(:all, :conditions => "#{QUOTED_TYPE} = 'Client'").length
      assert_equal 1, firm.clients.find(:all, :conditions => "name = 'Summit'").length
    end
D
Initial  
David Heinemeier Hansson 已提交
513 514 515
  end

  def test_find_all_sanitized
516 517 518 519 520 521 522
    assert_deprecated 'find_all' do
      firm = Firm.find_first
      assert_equal firm.clients.find_all("name = 'Summit'"), firm.clients.find_all(["name = '%s'", "Summit"])
      summit = firm.clients.find(:all, :conditions => "name = 'Summit'")
      assert_equal summit, firm.clients.find(:all, :conditions => ["name = ?", "Summit"])
      assert_equal summit, firm.clients.find(:all, :conditions => ["name = :name", { :name => "Summit" }])
    end
D
Initial  
David Heinemeier Hansson 已提交
523 524
  end

525
  def test_find_first
526 527 528 529 530 531 532
    assert_deprecated 'find_first' do
      firm = Firm.find_first
      client2 = Client.find(2)
      assert_equal firm.clients.first, firm.clients.find_first
      assert_equal client2, firm.clients.find_first("#{QUOTED_TYPE} = 'Client'")
      assert_equal client2, firm.clients.find(:first, :conditions => "#{QUOTED_TYPE} = 'Client'")
    end
533 534 535
  end

  def test_find_first_sanitized
536 537 538 539 540 541 542 543 544
    assert_deprecated 'find_first' do
      firm = Firm.find_first
      client2 = Client.find(2)
      assert_deprecated(/find_first/) do
        assert_equal client2, firm.clients.find_first(["#{QUOTED_TYPE} = ?", "Client"])
      end
      assert_equal client2, firm.clients.find(:first, :conditions => ["#{QUOTED_TYPE} = ?", 'Client'])
      assert_equal client2, firm.clients.find(:first, :conditions => ["#{QUOTED_TYPE} = :type", { :type => 'Client' }])
    end
545 546
  end

D
Initial  
David Heinemeier Hansson 已提交
547
  def test_find_in_collection
548 549
    assert_equal Client.find(2).name, companies(:first_firm).clients.find(2).name
    assert_raises(ActiveRecord::RecordNotFound) { companies(:first_firm).clients.find(6) }
D
Initial  
David Heinemeier Hansson 已提交
550 551
  end

552 553 554 555 556 557 558
  def test_find_grouped
    all_clients_of_firm1 = Client.find(:all, :conditions => "firm_id = 1")
    grouped_clients_of_firm1 = Client.find(:all, :conditions => "firm_id = 1", :group => "firm_id", :select => 'firm_id, count(id) as clients_count')
    assert_equal 2, all_clients_of_firm1.size
    assert_equal 1, grouped_clients_of_firm1.size
  end

D
Initial  
David Heinemeier Hansson 已提交
559 560 561
  def test_adding
    force_signal37_to_load_all_clients_of_firm
    natural = Client.new("name" => "Natural Company")
562 563 564 565
    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
D
Initial  
David Heinemeier Hansson 已提交
566
  end
567 568 569 570 571 572 573 574

  def test_adding_using_create
    first_firm = companies(:first_firm)
    assert_equal 2, first_firm.plain_clients.size
    natural = first_firm.plain_clients.create(:name => "Natural Company")
    assert_equal 3, first_firm.plain_clients.length
    assert_equal 3, first_firm.plain_clients.size
  end
D
Initial  
David Heinemeier Hansson 已提交
575 576
  
  def test_adding_a_mismatch_class
577 578 579
    assert_raises(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).clients_of_firm << nil }
    assert_raises(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).clients_of_firm << 1 }
    assert_raises(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).clients_of_firm << Topic.find(1) }
D
Initial  
David Heinemeier Hansson 已提交
580 581 582 583
  end
  
  def test_adding_a_collection
    force_signal37_to_load_all_clients_of_firm
584 585 586
    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
D
Initial  
David Heinemeier Hansson 已提交
587 588
  end

589 590 591 592 593 594
  def test_adding_before_save
    no_of_firms = Firm.count
    no_of_clients = Client.count
    new_firm = Firm.new("name" => "A New Firm, Inc")
    new_firm.clients_of_firm.push Client.new("name" => "Natural Company")
    new_firm.clients_of_firm << (c = Client.new("name" => "Apple"))
595 596
    assert new_firm.new_record?
    assert c.new_record?
597 598 599 600
    assert_equal 2, new_firm.clients_of_firm.size
    assert_equal no_of_firms, Firm.count      # Firm was not saved to database.
    assert_equal no_of_clients, Client.count  # Clients were not saved to database.
    assert new_firm.save
601 602
    assert !new_firm.new_record?
    assert !c.new_record?
603 604 605 606 607 608 609 610 611 612
    assert_equal new_firm, c.firm
    assert_equal no_of_firms+1, Firm.count      # Firm was saved to database.
    assert_equal no_of_clients+2, Client.count  # Clients were saved to database.
    assert_equal 2, new_firm.clients_of_firm.size
    assert_equal 2, new_firm.clients_of_firm(true).size
  end

  def test_invalid_adding
    firm = Firm.find(1)
    assert !(firm.clients_of_firm << c = Client.new)
613
    assert c.new_record?
614
    assert !firm.valid?
615
    assert !firm.save
616
    assert c.new_record?
617 618 619 620 621 622 623
  end

  def test_invalid_adding_before_save
    no_of_firms = Firm.count
    no_of_clients = Client.count
    new_firm = Firm.new("name" => "A New Firm, Inc")
    new_firm.clients_of_firm.concat([c = Client.new, Client.new("name" => "Apple")])
624
    assert c.new_record?
625
    assert !c.valid?
626
    assert !new_firm.valid?
627
    assert !new_firm.save
628 629
    assert c.new_record?
    assert new_firm.new_record?
630 631
  end

D
Initial  
David Heinemeier Hansson 已提交
632
  def test_build
633
    new_client = companies(:first_firm).clients_of_firm.build("name" => "Another Client")
D
Initial  
David Heinemeier Hansson 已提交
634
    assert_equal "Another Client", new_client.name
635
    assert new_client.new_record?
636 637
    assert_equal new_client, companies(:first_firm).clients_of_firm.last
    assert companies(:first_firm).save
638
    assert !new_client.new_record?
639
    assert_equal 2, companies(:first_firm).clients_of_firm(true).size
D
Initial  
David Heinemeier Hansson 已提交
640
  end
641

642
  def test_build_many
643
    new_clients = companies(:first_firm).clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}])
644 645
    assert_equal 2, new_clients.size

646 647
    assert companies(:first_firm).save
    assert_equal 3, companies(:first_firm).clients_of_firm(true).size
648 649
  end

650
  def test_build_without_loading_association
D
David Heinemeier Hansson 已提交
651
    first_topic = topics(:first)
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
    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

  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

679
  def test_invalid_build
680
    new_client = companies(:first_firm).clients_of_firm.build
681
    assert new_client.new_record?
682
    assert !new_client.valid?
683 684
    assert_equal new_client, companies(:first_firm).clients_of_firm.last
    assert !companies(:first_firm).save
685
    assert new_client.new_record?
686
    assert_equal 1, companies(:first_firm).clients_of_firm(true).size
687
  end
D
Initial  
David Heinemeier Hansson 已提交
688 689 690
  
  def test_create
    force_signal37_to_load_all_clients_of_firm
691
    new_client = companies(:first_firm).clients_of_firm.create("name" => "Another Client")
692
    assert !new_client.new_record?
693 694
    assert_equal new_client, companies(:first_firm).clients_of_firm.last
    assert_equal new_client, companies(:first_firm).clients_of_firm(true).last
D
Initial  
David Heinemeier Hansson 已提交
695
  end
696 697
  
  def test_create_many
698 699
    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
700
  end
D
Initial  
David Heinemeier Hansson 已提交
701

702 703 704 705 706 707 708 709
  def test_find_or_create
    number_of_clients = companies(:first_firm).clients.size
    the_client = companies(:first_firm).clients.find_or_create_by_name("Yet another client")
    assert_equal number_of_clients + 1, companies(:first_firm, :refresh).clients.size
    assert_equal the_client, companies(:first_firm).clients.find_or_create_by_name("Yet another client")
    assert_equal number_of_clients + 1, companies(:first_firm, :refresh).clients.size
  end

D
Initial  
David Heinemeier Hansson 已提交
710 711
  def test_deleting
    force_signal37_to_load_all_clients_of_firm
712 713 714
    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
D
Initial  
David Heinemeier Hansson 已提交
715 716
  end

717 718 719 720 721 722 723 724
  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

D
Initial  
David Heinemeier Hansson 已提交
725 726
  def test_deleting_a_collection
    force_signal37_to_load_all_clients_of_firm
727 728 729 730 731
    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
D
Initial  
David Heinemeier Hansson 已提交
732
  end
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
  
  def test_delete_all
    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_all
    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
D
Initial  
David Heinemeier Hansson 已提交
752

753 754 755 756 757 758 759 760 761 762 763 764
  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

    firm.clients_of_firm.clear

    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.
765 766 767
    assert_nothing_raised do
      assert Client.find(client_id).firm.nil?
    end
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
  end

  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.
    assert Client.find_by_id(client_id).nil?
  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

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

793 794 795 796 797 798
    # :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
799
    assert_equal [3], Client.destroyed_client_ids[firm.id]
800 801 802

    # Should be destroyed since the association is exclusively dependent.
    assert Client.find_by_id(client_id).nil?
803
  end                                                    
D
Initial  
David Heinemeier Hansson 已提交
804

805 806 807 808 809 810 811 812 813
  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

D
Initial  
David Heinemeier Hansson 已提交
814 815
  def test_deleting_a_item_which_is_not_in_the_collection
    force_signal37_to_load_all_clients_of_firm
816
    summit = Client.find_by_name('Summit')
817 818 819
    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
D
Initial  
David Heinemeier Hansson 已提交
820 821 822 823 824
    assert_equal 2, summit.client_of
  end

  def test_deleting_type_mismatch
    david = Developer.find(1)
825
    david.projects.reload
D
Initial  
David Heinemeier Hansson 已提交
826 827 828 829 830
    assert_raises(ActiveRecord::AssociationTypeMismatch) { david.projects.delete(1) }
  end

  def test_deleting_self_type_mismatch
    david = Developer.find(1)
831
    david.projects.reload
D
Initial  
David Heinemeier Hansson 已提交
832 833 834 835 836
    assert_raises(ActiveRecord::AssociationTypeMismatch) { david.projects.delete(Project.find(1).developers) }
  end

  def test_destroy_all
    force_signal37_to_load_all_clients_of_firm
837 838 839 840
    assert !companies(:first_firm).clients_of_firm.empty?, "37signals has clients after load"
    companies(:first_firm).clients_of_firm.destroy_all
    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"
D
Initial  
David Heinemeier Hansson 已提交
841 842 843
  end

  def test_dependence
844 845 846 847
    firm = companies(:first_firm)
    assert_equal 2, firm.clients.size
    firm.destroy
    assert Client.find(:all, :conditions => "firm_id=#{firm.id}").empty?
848 849 850
  end

  def test_destroy_dependent_when_deleted_from_association
851
    firm = Firm.find(:first)
852 853 854 855 856 857 858 859
    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
D
Initial  
David Heinemeier Hansson 已提交
860 861
  end

862 863 864
  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"
865
    silly_reply = reply.replies.create "title" => "neat and simple", "content" => "ain't complaining"
866 867 868 869
    
    assert_nothing_raised { topic.destroy }
  end

870
  uses_transaction :test_dependence_with_transaction_support_on_failure
D
Initial  
David Heinemeier Hansson 已提交
871
  def test_dependence_with_transaction_support_on_failure
872
    firm = companies(:first_firm)
D
Initial  
David Heinemeier Hansson 已提交
873
    clients = firm.clients
874
    assert_equal 2, clients.length
D
Initial  
David Heinemeier Hansson 已提交
875 876 877 878
    clients.last.instance_eval { def before_destroy() raise "Trigger rollback" end }

    firm.destroy rescue "do nothing"

879
    assert_equal 2, Client.find(:all, :conditions => "firm_id=#{firm.id}").size
D
Initial  
David Heinemeier Hansson 已提交
880 881 882
  end

  def test_dependence_on_account
883
    num_accounts = Account.count
884
    companies(:first_firm).destroy
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
    assert_equal num_accounts - 1, Account.count
  end

  def test_depends_and_nullify
    num_accounts = Account.count
    num_companies = Company.count
    
    core = companies(:rails_core)
    assert_equal accounts(:rails_core_account), core.account
    assert_equal [companies(:leetsoft), companies(: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
D
Initial  
David Heinemeier Hansson 已提交
902 903 904
  end

  def test_included_in_collection
905
    assert companies(:first_firm).clients.include?(Client.find(2))
D
Initial  
David Heinemeier Hansson 已提交
906 907 908
  end

  def test_adding_array_and_collection
909
    assert_nothing_raised { Firm.find(:first).clients + Firm.find(:all).last.clients }
D
Initial  
David Heinemeier Hansson 已提交
910
  end
911 912 913 914 915

  def test_find_all_without_conditions
    firm = companies(:first_firm)
    assert_equal 2, firm.clients.find(:all).length
  end
916 917

  def test_replace_with_less
918
    firm = Firm.find(:first)
919 920 921 922
    firm.clients = [companies(:first_client)]
    assert firm.save, "Could not save firm"
    firm.reload
    assert_equal 1, firm.clients.length
923 924
  end 
  
925 926
  
  def test_replace_with_new
927
    firm = Firm.find(:first)
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
    new_client = Client.new("name" => "New Client")
    firm.clients = [companies(:second_client),new_client]
    firm.save
    firm.reload
    assert_equal 2, firm.clients.length
    assert !firm.clients.include?(:first_client)
  end
  
  def test_replace_on_new_object
    firm = Firm.new("name" => "New Firm")
    firm.clients = [companies(:second_client), Client.new("name" => "New Client")]
    assert firm.save
    firm.reload
    assert_equal 2, firm.clients.length
    assert firm.clients.include?(Client.find_by_name("New Client"))
  end
  
945 946 947 948
  def test_get_ids
    assert_equal [companies(:first_client).id, companies(:second_client).id], companies(:first_firm).client_ids
  end
  
949 950 951 952 953 954 955 956
  def test_assign_ids
    firm = Firm.new("name" => "Apple")
    firm.client_ids = [companies(:first_client).id, companies(:second_client).id]
    firm.save
    firm.reload
    assert_equal 2, firm.clients.length
    assert firm.clients.include?(companies(:second_client))
  end
957 958 959 960 961 962 963 964 965 966

  def test_assign_ids_ignoring_blanks
    firm = Firm.new("name" => "Apple")
    firm.client_ids = [companies(:first_client).id, nil, companies(:second_client).id, '']
    firm.save
    firm.reload
    assert_equal 2, firm.clients.length
    assert firm.clients.include?(companies(:second_client))
  end

D
Initial  
David Heinemeier Hansson 已提交
967 968 969
end

class BelongsToAssociationsTest < Test::Unit::TestCase
970
  fixtures :accounts, :companies, :developers, :projects, :topics,
971
           :developers_projects, :computers, :authors, :posts
D
David Heinemeier Hansson 已提交
972
  
D
Initial  
David Heinemeier Hansson 已提交
973 974
  def test_belongs_to
    Client.find(3).firm.name
975
    assert_equal companies(:first_firm).name, Client.find(3).firm.name
D
Initial  
David Heinemeier Hansson 已提交
976 977 978
    assert !Client.find(3).firm.nil?, "Microsoft should have a firm"   
  end

979 980 981 982 983
  def test_proxy_assignment
    account = Account.find(1)
    assert_nothing_raised { account.firm = account.firm }
  end

984 985 986 987 988
  def test_triple_equality
    assert Client.find(3).firm === Firm
    assert Firm === Client.find(3).firm
  end

D
Initial  
David Heinemeier Hansson 已提交
989 990 991 992 993 994 995 996 997 998 999 1000
  def test_type_mismatch
    assert_raise(ActiveRecord::AssociationTypeMismatch) { Account.find(1).firm = 1 }
    assert_raise(ActiveRecord::AssociationTypeMismatch) { Account.find(1).firm = Project.find(1) }
  end

  def test_natural_assignment
    apple = Firm.create("name" => "Apple")
    citibank = Account.create("credit_limit" => 10)
    citibank.firm = apple
    assert_equal apple.id, citibank.firm_id
  end
  
1001 1002 1003 1004
  def test_creating_the_belonging_object
    citibank = Account.create("credit_limit" => 10)
    apple    = citibank.create_firm("name" => "Apple")
    assert_equal apple, citibank.firm
1005 1006 1007
    citibank.save
    citibank.reload
    assert_equal apple, citibank.firm
1008 1009 1010 1011 1012 1013 1014 1015 1016
  end

  def test_building_the_belonging_object
    citibank = Account.create("credit_limit" => 10)
    apple    = citibank.build_firm("name" => "Apple")
    citibank.save
    assert_equal apple.id, citibank.firm_id
  end
  
D
Initial  
David Heinemeier Hansson 已提交
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
  def test_natural_assignment_to_nil
    client = Client.find(3)
    client.firm = nil
    client.save
    assert_nil client.firm(true)
    assert_nil client.client_of
  end
  
  def test_with_different_class_name
    assert_equal Company.find(1).name, Company.find(3).firm_with_other_name.name
    assert_not_nil Company.find(3).firm_with_other_name, "Microsoft should have a firm"
  end

  def test_with_condition
    assert_equal Company.find(1).name, Company.find(3).firm_with_condition.name
    assert_not_nil Company.find(3).firm_with_condition, "Microsoft should have a firm"
  end
  
  def test_belongs_to_counter
    debate = Topic.create("title" => "debate")
    assert_equal 0, debate.send(:read_attribute, "replies_count"), "No replies yet"

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

    trash.destroy
    assert_equal 0, Topic.find(debate.id).send(:read_attribute, "replies_count"), "First reply deleted"
  end

1046 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_belongs_to_counter_with_reassigning
    t1 = Topic.create("title" => "t1")
    t2 = Topic.create("title" => "t2")
    r1 = Reply.new("title" => "r1", "content" => "r1")
    r1.topic = t1

    assert r1.save
    assert_equal 1, Topic.find(t1.id).replies.size
    assert_equal 0, Topic.find(t2.id).replies.size

    r1.topic = Topic.find(t2.id)

    assert r1.save
    assert_equal 0, Topic.find(t1.id).replies.size
    assert_equal 1, Topic.find(t2.id).replies.size

    r1.topic = nil

    assert_equal 0, Topic.find(t1.id).replies.size
    assert_equal 0, Topic.find(t2.id).replies.size

    r1.topic = t1

    assert_equal 1, Topic.find(t1.id).replies.size
    assert_equal 0, Topic.find(t2.id).replies.size

    r1.destroy

    assert_equal 0, Topic.find(t1.id).replies.size
    assert_equal 0, Topic.find(t2.id).replies.size
  end

1078
  def test_assignment_before_parent_saved
1079
    client = Client.find(:first)
1080 1081 1082
    apple = Firm.new("name" => "Apple")
    client.firm = apple
    assert_equal apple, client.firm
1083
    assert apple.new_record?
1084 1085
    assert client.save
    assert apple.save
1086
    assert !apple.new_record?
1087 1088 1089 1090 1091 1092 1093 1094
    assert_equal apple, client.firm
    assert_equal apple, client.firm(true)
  end

  def test_assignment_before_child_saved
    final_cut = Client.new("name" => "Final Cut")
    firm = Firm.find(1)
    final_cut.firm = firm
1095
    assert final_cut.new_record?
1096
    assert final_cut.save
1097 1098
    assert !final_cut.new_record?
    assert !firm.new_record?
1099 1100 1101 1102 1103 1104 1105 1106
    assert_equal firm, final_cut.firm
    assert_equal firm, final_cut.firm(true)
  end

  def test_assignment_before_either_saved
    final_cut = Client.new("name" => "Final Cut")
    apple = Firm.new("name" => "Apple")
    final_cut.firm = apple
1107 1108
    assert final_cut.new_record?
    assert apple.new_record?
1109
    assert final_cut.save
1110 1111
    assert !final_cut.new_record?
    assert !apple.new_record?
1112 1113 1114 1115
    assert_equal apple, final_cut.firm
    assert_equal apple, final_cut.firm(true)
  end

D
David Heinemeier Hansson 已提交
1116 1117
  def test_new_record_with_foreign_key_but_no_object
    c = Client.new("firm_id" => 1)
1118
    assert_equal Firm.find(:first), c.firm_with_basic_id
D
David Heinemeier Hansson 已提交
1119 1120
  end

1121 1122 1123 1124 1125
  def test_forgetting_the_load_when_foreign_key_enters_late
    c = Client.new
    assert_nil c.firm_with_basic_id

    c.firm_id = 1
1126
    assert_equal Firm.find(:first), c.firm_with_basic_id
1127 1128
  end

1129
  def test_field_name_same_as_foreign_key
1130
    computer = Computer.find(1)
1131
    assert_not_nil computer.developer, ":foreign key == attribute didn't lock up" # '
1132 1133
  end

1134 1135 1136 1137 1138 1139 1140 1141
  def test_counter_cache
    topic = Topic.create :title => "Zoom-zoom-zoom"
    assert_equal 0, topic[:replies_count]
    
    reply = Reply.create(:title => "re: zoom", :content => "speedy quick!")
    reply.topic = topic

    assert_equal 1, topic.reload[:replies_count]
1142 1143 1144 1145
    assert_equal 1, topic.replies.size

    topic[:replies_count] = 15
    assert_equal 15, topic.replies.size
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
  end

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

    silly = SillyReply.create(:title => "gaga", :content => "boo-boo")
    silly.reply = reply

    assert_equal 1, reply.reload[:replies_count]
1156
    assert_equal 1, reply.replies.size
D
Initial  
David Heinemeier Hansson 已提交
1157

1158 1159
    reply[:replies_count] = 17
    assert_equal 17, reply.replies.size
D
Initial  
David Heinemeier Hansson 已提交
1160
  end
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180

  def test_store_two_association_with_one_save
    num_orders = Order.count
    num_customers = Customer.count
    order = Order.new 

    customer1 = order.billing = Customer.new
    customer2 = order.shipping = Customer.new 
    assert order.save
    assert_equal customer1, order.billing
    assert_equal customer2, order.shipping

    order.reload

    assert_equal customer1, order.billing
    assert_equal customer2, order.shipping        

    assert_equal num_orders +1, Order.count
    assert_equal num_customers +2, Customer.count
  end
1181

1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
  
  def test_store_association_in_two_relations_with_one_save
    num_orders = Order.count
    num_customers = Customer.count
    order = Order.new 
    
    customer = order.billing = order.shipping = Customer.new 
    assert order.save
    assert_equal customer, order.billing
    assert_equal customer, order.shipping
    
    order.reload
    
    assert_equal customer, order.billing
    assert_equal customer, order.shipping        
    
    assert_equal num_orders +1, Order.count
    assert_equal num_customers +1, Customer.count
  end
J
Jamis Buck 已提交
1201

1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245
  def test_store_association_in_two_relations_with_one_save_in_existing_object
    num_orders = Order.count
    num_customers = Customer.count
    order = Order.create
    
    customer = order.billing = order.shipping = Customer.new 
    assert order.save
    assert_equal customer, order.billing
    assert_equal customer, order.shipping
    
    order.reload
    
    assert_equal customer, order.billing
    assert_equal customer, order.shipping        
    
    assert_equal num_orders +1, Order.count
    assert_equal num_customers +1, Customer.count
  end
  
  def test_store_association_in_two_relations_with_one_save_in_existing_object_with_values
    num_orders = Order.count
    num_customers = Customer.count
    order = Order.create
    
    customer = order.billing = order.shipping = Customer.new 
    assert order.save
    assert_equal customer, order.billing
    assert_equal customer, order.shipping
    
    order.reload
    
    customer = order.billing = order.shipping = Customer.new 
    
    assert order.save
    order.reload    
    
    assert_equal customer, order.billing
    assert_equal customer, order.shipping        
    
    assert_equal num_orders +1, Order.count
    assert_equal num_customers +2, Customer.count
  end
  
  
J
Jamis Buck 已提交
1246
  def test_association_assignment_sticks
1247
    post = Post.find(:first)
1248

1249
    author1, author2 = Author.find(:all, :limit => 2)
1250 1251
    assert_not_nil author1
    assert_not_nil author2
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264

    # make sure the association is loaded
    post.author

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

    # save and reload
    post.save!
    post.reload

    # the author id of the post should be the id we set
    assert_equal post.author_id, author2.id
J
Jamis Buck 已提交
1265
  end
1266
  
D
Initial  
David Heinemeier Hansson 已提交
1267 1268 1269
end


1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
class ProjectWithAfterCreateHook < ActiveRecord::Base
  set_table_name 'projects'
  has_and_belongs_to_many :developers,
    :class_name => "DeveloperForProjectWithAfterCreateHook",
    :join_table => "developers_projects",
    :foreign_key => "project_id",
    :association_foreign_key => "developer_id"

  after_create :add_david

  def add_david
    david = DeveloperForProjectWithAfterCreateHook.find_by_name('David')
    david.projects << self
  end
end

class DeveloperForProjectWithAfterCreateHook < ActiveRecord::Base
  set_table_name 'developers'
  has_and_belongs_to_many :projects,
    :class_name => "ProjectWithAfterCreateHook",
    :join_table => "developers_projects",
    :association_foreign_key => "project_id",
    :foreign_key => "developer_id"
end


D
Initial  
David Heinemeier Hansson 已提交
1296
class HasAndBelongsToManyAssociationsTest < Test::Unit::TestCase
1297
  fixtures :accounts, :companies, :categories, :posts, :categories_posts, :developers, :projects, :developers_projects
D
Initial  
David Heinemeier Hansson 已提交
1298 1299 1300 1301 1302 1303 1304 1305 1306
  
  def test_has_and_belongs_to_many
    david = Developer.find(1)

    assert !david.projects.empty?
    assert_equal 2, david.projects.size

    active_record = Project.find(1)
    assert !active_record.developers.empty?
1307
    assert_equal 3, active_record.developers.size
1308
    assert active_record.developers.include?(david)
D
Initial  
David Heinemeier Hansson 已提交
1309
  end
1310

1311 1312 1313 1314 1315
  def test_triple_equality
    assert !(Array === Developer.find(1).projects)
    assert Developer.find(1).projects === Array
  end

D
Initial  
David Heinemeier Hansson 已提交
1316 1317
  def test_adding_single
    jamis = Developer.find(2)
1318
    jamis.projects.reload # causing the collection to load 
D
Initial  
David Heinemeier Hansson 已提交
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
    action_controller = Project.find(2)
    assert_equal 1, jamis.projects.size
    assert_equal 1, action_controller.developers.size    
    
    jamis.projects << action_controller

    assert_equal 2, jamis.projects.size
    assert_equal 2, jamis.projects(true).size
    assert_equal 2, action_controller.developers(true).size
  end

  def test_adding_type_mismatch
    jamis = Developer.find(2)
    assert_raise(ActiveRecord::AssociationTypeMismatch) { jamis.projects << nil }
    assert_raise(ActiveRecord::AssociationTypeMismatch) { jamis.projects << 1 }
  end

  def test_adding_from_the_project
    jamis = Developer.find(2)
    action_controller = Project.find(2)
1339
    action_controller.developers.reload
D
Initial  
David Heinemeier Hansson 已提交
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
    assert_equal 1, jamis.projects.size
    assert_equal 1, action_controller.developers.size

    action_controller.developers << jamis 
    
    assert_equal 2, jamis.projects(true).size
    assert_equal 2, action_controller.developers.size
    assert_equal 2, action_controller.developers(true).size
  end

1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
  def test_adding_from_the_project_fixed_timestamp
    jamis = Developer.find(2)
    action_controller = Project.find(2)
    action_controller.developers.reload
    assert_equal 1, jamis.projects.size
    assert_equal 1, action_controller.developers.size
    updated_at = jamis.updated_at

    action_controller.developers << jamis

    assert_equal updated_at, jamis.updated_at
    assert_equal 2, jamis.projects(true).size
    assert_equal 2, action_controller.developers.size
    assert_equal 2, action_controller.developers(true).size
  end

D
Initial  
David Heinemeier Hansson 已提交
1366
  def test_adding_multiple
1367
    aredridel = Developer.new("name" => "Aredridel")
1368 1369 1370 1371 1372
    aredridel.save
    aredridel.projects.reload
    aredridel.projects.push(Project.find(1), Project.find(2))
    assert_equal 2, aredridel.projects.size
    assert_equal 2, aredridel.projects(true).size
D
Initial  
David Heinemeier Hansson 已提交
1373 1374 1375
  end

  def test_adding_a_collection
1376
    aredridel = Developer.new("name" => "Aredridel")
1377 1378 1379 1380 1381
    aredridel.save
    aredridel.projects.reload
    aredridel.projects.concat([Project.find(1), Project.find(2)])
    assert_equal 2, aredridel.projects.size
    assert_equal 2, aredridel.projects(true).size
D
Initial  
David Heinemeier Hansson 已提交
1382
  end
1383

1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
  def test_adding_uses_default_values_on_join_table
    ac = projects(:action_controller)
    assert !developers(:jamis).projects.include?(ac)
    developers(:jamis).projects << ac

    assert developers(:jamis, :reload).projects.include?(ac)
    project = developers(:jamis).projects.detect { |p| p == ac }
    assert_equal 1, project.access_level.to_i
  end

  def test_adding_uses_explicit_values_on_join_table
    ac = projects(:action_controller)
    assert !developers(:jamis).projects.include?(ac)
1397 1398 1399
    assert_deprecated do
      developers(:jamis).projects.push_with_attributes(ac, :access_level => 3)
    end
1400 1401 1402 1403 1404 1405

    assert developers(:jamis, :reload).projects.include?(ac)
    project = developers(:jamis).projects.detect { |p| p == ac }
    assert_equal 3, project.access_level.to_i
  end

1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
  def test_hatbm_attribute_access_and_respond_to
    project = developers(:jamis).projects[0]
    assert project.has_attribute?("name")
    assert project.has_attribute?("joined_on")
    assert project.has_attribute?("access_level")
    assert project.respond_to?("name")
    assert project.respond_to?("name=")
    assert project.respond_to?("name?")
    assert project.respond_to?("joined_on")
    assert project.respond_to?("joined_on=")
    assert project.respond_to?("joined_on?")
    assert project.respond_to?("access_level")
    assert project.respond_to?("access_level=")
    assert project.respond_to?("access_level?")
  end

1422 1423 1424
  def test_habtm_adding_before_save
    no_of_devels = Developer.count
    no_of_projects = Project.count
1425
    aredridel = Developer.new("name" => "Aredridel")
1426
    aredridel.projects.concat([Project.find(1), p = Project.new("name" => "Projekt")])
1427 1428
    assert aredridel.new_record?
    assert p.new_record?
1429
    assert aredridel.save
1430
    assert !aredridel.new_record?
1431 1432
    assert_equal no_of_devels+1, Developer.count
    assert_equal no_of_projects+1, Project.count
1433 1434
    assert_equal 2, aredridel.projects.size
    assert_equal 2, aredridel.projects(true).size
1435 1436
  end

1437 1438 1439 1440 1441
  def test_habtm_adding_before_save_with_join_attributes
    no_of_devels = Developer.count
    no_of_projects = Project.count
    now = Date.today
    ken = Developer.new("name" => "Ken")
1442 1443 1444
    assert_deprecated do
      ken.projects.push_with_attributes( Project.find(1), :joined_on => now )
    end
1445
    p = Project.new("name" => "Foomatic")
1446 1447 1448
    assert_deprecated do
      ken.projects.push_with_attributes( p, :joined_on => now )
    end
1449 1450
    assert ken.new_record?
    assert p.new_record?
1451
    assert ken.save
1452
    assert !ken.new_record?
1453 1454 1455 1456 1457 1458
    assert_equal no_of_devels+1, Developer.count
    assert_equal no_of_projects+1, Project.count
    assert_equal 2, ken.projects.size
    assert_equal 2, ken.projects(true).size

    kenReloaded = Developer.find_by_name 'Ken'
1459
    kenReloaded.projects.each {|prj| assert_date_from_db(now, prj.joined_on)}
1460 1461
  end

1462 1463 1464
  def test_habtm_saving_multiple_relationships
    new_project = Project.new("name" => "Grimetime")
    amount_of_developers = 4
1465 1466
    developers = (0...amount_of_developers).collect {|i| Developer.create(:name => "JME #{i}") }.reverse

1467 1468 1469
    new_project.developer_ids = [developers[0].id, developers[1].id]
    new_project.developers_with_callback_ids = [developers[2].id, developers[3].id]
    assert new_project.save
1470

1471 1472
    new_project.reload
    assert_equal amount_of_developers, new_project.developers.size
1473 1474 1475 1476 1477 1478
    assert_equal developers, new_project.developers
  end

  def test_habtm_unique_order_preserved
    assert_equal [developers(:poor_jamis), developers(:jamis), developers(:david)], projects(:active_record).non_unique_developers
    assert_equal [developers(:poor_jamis), developers(:jamis), developers(:david)], projects(:active_record).developers
1479 1480
  end

1481 1482 1483 1484
  def test_build
    devel = Developer.find(1)
    proj = devel.projects.build("name" => "Projekt")
    assert_equal devel.projects.last, proj
1485
    assert proj.new_record?
1486
    devel.save
1487
    assert !proj.new_record?
1488
    assert_equal devel.projects.last, proj
R
Rick Olson 已提交
1489
    assert_equal Developer.find(1).projects.sort_by(&:id).last, proj  # prove join table is updated
1490 1491 1492 1493 1494 1495 1496
  end
  
  def test_build_by_new_record
    devel = Developer.new(:name => "Marcel", :salary => 75000)
    proj1 = devel.projects.build(:name => "Make bed")
    proj2 = devel.projects.build(:name => "Lie in it")
    assert_equal devel.projects.last, proj2
1497
    assert proj2.new_record?
1498
    devel.save
1499 1500
    assert !devel.new_record?
    assert !proj2.new_record?
1501 1502
    assert_equal devel.projects.last, proj2
    assert_equal Developer.find_by_name("Marcel").projects.last, proj2  # prove join table is updated
1503 1504 1505 1506 1507 1508
  end
  
  def test_create
    devel = Developer.find(1)
    proj = devel.projects.create("name" => "Projekt")
    assert_equal devel.projects.last, proj
1509
    assert !proj.new_record?
R
Rick Olson 已提交
1510
    assert_equal Developer.find(1).projects.sort_by(&:id).last, proj  # prove join table is updated
1511 1512 1513 1514 1515 1516 1517
  end
  
  def test_create_by_new_record
    devel = Developer.new(:name => "Marcel", :salary => 75000)
    proj1 = devel.projects.create(:name => "Make bed")
    proj2 = devel.projects.create(:name => "Lie in it")
    assert_equal devel.projects.last, proj2
1518
    assert proj2.new_record?
1519
    devel.save
1520 1521
    assert !devel.new_record?
    assert !proj2.new_record?
1522 1523
    assert_equal devel.projects.last, proj2
    assert_equal Developer.find_by_name("Marcel").projects.last, proj2  # prove join table is updated
1524
  end
D
Initial  
David Heinemeier Hansson 已提交
1525 1526
  
  def test_uniq_after_the_fact
1527 1528 1529 1530
    developers(:jamis).projects << projects(:active_record)
    developers(:jamis).projects << projects(:active_record)
    assert_equal 3, developers(:jamis).projects.size
    assert_equal 1, developers(:jamis).projects.uniq.size
D
Initial  
David Heinemeier Hansson 已提交
1531 1532 1533
  end

  def test_uniq_before_the_fact
1534 1535
    projects(:active_record).developers << developers(:jamis)
    projects(:active_record).developers << developers(:david)
1536
    assert_equal 3, projects(:active_record, :reload).developers.size
D
Initial  
David Heinemeier Hansson 已提交
1537 1538 1539 1540 1541
  end
  
  def test_deleting
    david = Developer.find(1)
    active_record = Project.find(1)
1542
    david.projects.reload
D
Initial  
David Heinemeier Hansson 已提交
1543
    assert_equal 2, david.projects.size
1544
    assert_equal 3, active_record.developers.size
D
Initial  
David Heinemeier Hansson 已提交
1545 1546 1547 1548 1549

    david.projects.delete(active_record)
    
    assert_equal 1, david.projects.size
    assert_equal 1, david.projects(true).size
1550
    assert_equal 2, active_record.developers(true).size
D
Initial  
David Heinemeier Hansson 已提交
1551 1552 1553 1554
  end

  def test_deleting_array
    david = Developer.find(1)
1555
    david.projects.reload
1556
    david.projects.delete(Project.find(:all))
D
Initial  
David Heinemeier Hansson 已提交
1557 1558 1559 1560
    assert_equal 0, david.projects.size
    assert_equal 0, david.projects(true).size
  end

1561 1562 1563 1564
  def test_deleting_with_sql
    david = Developer.find(1)
    active_record = Project.find(1)
    active_record.developers.reload
1565
    assert_equal 3, active_record.developers_by_sql.size
1566 1567
    
    active_record.developers_by_sql.delete(david)
1568
    assert_equal 2, active_record.developers_by_sql(true).size
1569 1570 1571 1572 1573
  end

  def test_deleting_array_with_sql
    active_record = Project.find(1)
    active_record.developers.reload
1574
    assert_equal 3, active_record.developers_by_sql.size
1575
    
1576
    active_record.developers_by_sql.delete(Developer.find(:all))
1577 1578 1579
    assert_equal 0, active_record.developers_by_sql(true).size
  end

D
Initial  
David Heinemeier Hansson 已提交
1580 1581
  def test_deleting_all
    david = Developer.find(1)
1582
    david.projects.reload
D
Initial  
David Heinemeier Hansson 已提交
1583 1584 1585 1586 1587 1588
    david.projects.clear
    assert_equal 0, david.projects.size
    assert_equal 0, david.projects(true).size
  end

  def test_removing_associations_on_destroy
1589 1590 1591 1592 1593
    david = DeveloperWithBeforeDestroyRaise.find(1)
    assert !david.projects.empty?
    assert_nothing_raised { david.destroy }
    assert david.projects.empty?
    assert DeveloperWithBeforeDestroyRaise.connection.select_all("SELECT * FROM developers_projects WHERE developer_id = 1").empty?
D
Initial  
David Heinemeier Hansson 已提交
1594
  end
1595

D
Initial  
David Heinemeier Hansson 已提交
1596
  def test_additional_columns_from_join_table
1597
    assert_date_from_db Date.new(2004, 10, 10), Developer.find(1).projects.first.joined_on
D
Initial  
David Heinemeier Hansson 已提交
1598 1599 1600 1601
  end
  
  def test_destroy_all
    david = Developer.find(1)
1602
    david.projects.reload
D
Initial  
David Heinemeier Hansson 已提交
1603 1604 1605 1606 1607 1608 1609
    assert !david.projects.empty?
    david.projects.destroy_all
    assert david.projects.empty?
    assert david.projects(true).empty?
  end

  def test_rich_association
1610
    jamis = developers(:jamis)
1611 1612 1613 1614
    assert_deprecated 'push_with_attributes' do
      jamis.projects.push_with_attributes(projects(:action_controller), :joined_on => Date.today)
    end

1615 1616
    assert_date_from_db Date.today, jamis.projects.select { |p| p.name == projects(:action_controller).name }.first.joined_on
    assert_date_from_db Date.today, developers(:jamis).projects.select { |p| p.name == projects(:action_controller).name }.first.joined_on
D
Initial  
David Heinemeier Hansson 已提交
1617 1618 1619
  end

  def test_associations_with_conditions
1620
    assert_equal 3, projects(:active_record).developers.size
1621
    assert_equal 1, projects(:active_record).developers_named_david.size
1622
    assert_equal 1, projects(:active_record).developers_named_david_with_hash_conditions.size
1623 1624

    assert_equal developers(:david), projects(:active_record).developers_named_david.find(developers(:david).id)
1625
    assert_equal developers(:david), projects(:active_record).developers_named_david_with_hash_conditions.find(developers(:david).id)
1626 1627
    assert_equal developers(:david), projects(:active_record).salaried_developers.find(developers(:david).id)

1628
    projects(:active_record).developers_named_david.clear
1629
    assert_equal 2, projects(:active_record, :reload).developers.size
D
Initial  
David Heinemeier Hansson 已提交
1630 1631 1632 1633
  end
  
  def test_find_in_association
    # Using sql
1634
    assert_equal developers(:david), projects(:active_record).developers.find(developers(:david).id), "SQL find"
D
Initial  
David Heinemeier Hansson 已提交
1635 1636
    
    # Using ruby
1637 1638 1639
    active_record = projects(:active_record)
    active_record.developers.reload
    assert_equal developers(:david), active_record.developers.find(developers(:david).id), "Ruby find"
D
Initial  
David Heinemeier Hansson 已提交
1640
  end
1641

1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653
  def test_find_in_association_with_custom_finder_sql
    assert_equal developers(:david), projects(:active_record).developers_with_finder_sql.find(developers(:david).id), "SQL find"
   
    active_record = projects(:active_record)
    active_record.developers_with_finder_sql.reload
    assert_equal developers(:david), active_record.developers_with_finder_sql.find(developers(:david).id), "Ruby find"
  end

  def test_find_in_association_with_custom_finder_sql_and_string_id
    assert_equal developers(:david), projects(:active_record).developers_with_finder_sql.find(developers(:david).id.to_s), "SQL find"
  end

1654 1655 1656
  def test_find_with_merged_options
    assert_equal 1, projects(:active_record).limited_developers.size
    assert_equal 1, projects(:active_record).limited_developers.find(:all).size
1657
    assert_equal 3, projects(:active_record).limited_developers.find(:all, :limit => nil).size
1658
  end
1659

1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671
  def test_new_with_values_in_collection
    jamis = DeveloperForProjectWithAfterCreateHook.find_by_name('Jamis')
    david = DeveloperForProjectWithAfterCreateHook.find_by_name('David')
    project = ProjectWithAfterCreateHook.new(:name => "Cooking with Bertie")
    project.developers << jamis
    project.save!
    project.reload

    assert project.developers.include?(jamis)
    assert project.developers.include?(david)
  end

1672
  def test_find_in_association_with_options
1673
    developers = projects(:active_record).developers.find(:all)
1674
    assert_equal 3, developers.size
1675
    
1676 1677
    assert_equal developers(:poor_jamis), projects(:active_record).developers.find(:first, :conditions => "salary < 10000")
    assert_equal developers(:jamis),      projects(:active_record).developers.find(:first, :order => "salary DESC")
1678
  end
1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700
  
  def test_replace_with_less
    david = developers(:david)
    david.projects = [projects(:action_controller)]
    assert david.save
    assert_equal 1, david.projects.length
  end

  def test_replace_with_new
    david = developers(:david)
    david.projects = [projects(:action_controller), Project.new("name" => "ActionWebSearch")]
    david.save
    assert_equal 2, david.projects.length
    assert !david.projects.include?(projects(:active_record))
  end
  
  def test_replace_on_new_object
    new_developer = Developer.new("name" => "Matz")
    new_developer.projects = [projects(:action_controller), Project.new("name" => "ActionWebSearch")]
    new_developer.save
    assert_equal 2, new_developer.projects.length
  end
1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713

  def test_consider_type
    developer = Developer.find(:first)
    special_project = SpecialProject.create("name" => "Special Project")
  
    other_project = developer.projects.first
    developer.special_projects << special_project
    developer.reload
  
    assert developer.projects.include?(special_project)
    assert developer.special_projects.include?(special_project)
    assert !developer.special_projects.include?(other_project)
  end
1714 1715 1716 1717 1718 1719 1720
  
  def test_update_attributes_after_push_without_duplicate_join_table_rows
    developer = Developer.new("name" => "Kano")
    project = SpecialProject.create("name" => "Special Project")
    assert developer.save
    developer.projects << project
    developer.update_attribute("name", "Bruza")
1721 1722 1723 1724 1725
    assert_equal 1, Developer.connection.select_value(<<-end_sql).to_i
      SELECT count(*) FROM developers_projects
      WHERE project_id = #{project.id}
      AND developer_id = #{developer.id}
    end_sql
1726
  end
1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745
  
  def test_updating_attributes_on_non_rich_associations
    welcome = categories(:technology).posts.first
    welcome.title = "Something else"
    assert welcome.save!
  end
  
  def test_updating_attributes_on_rich_associations
    david = projects(:action_controller).developers.first
    david.name = "DHH"
    assert_raises(ActiveRecord::ReadOnlyRecord) { david.save! }
  end

  
  def test_updating_attributes_on_rich_associations_with_limited_find
    david = projects(:action_controller).developers.find(:all, :select => "developers.*").first
    david.name = "DHH"
    assert david.save!
  end
1746 1747

  def test_join_table_alias
1748
    assert_equal 3, Developer.find(:all, :include => {:projects => :developers}, :conditions => 'developers_projects_join.joined_on IS NOT NULL').size
1749
  end
1750 1751
  
  def test_join_with_group
1752 1753 1754 1755 1756 1757 1758
    group = Developer.columns.inject([]) do |g, c|
      g << "developers.#{c.name}"
      g << "developers_projects_2.#{c.name}"
    end
    Project.columns.each { |c| group << "projects.#{c.name}" }

    assert_equal 3, Developer.find(:all, :include => {:projects => :developers}, :conditions => 'developers_projects_join.joined_on IS NOT NULL', :group => group.join(",")).size
1759
  end
1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784

  def test_get_ids
    assert_equal [projects(:active_record).id, projects(:action_controller).id], developers(:david).project_ids
    assert_equal [projects(:active_record).id], developers(:jamis).project_ids
  end

  def test_assign_ids
    developer = Developer.new("name" => "Joe")
    developer.project_ids = [projects(:active_record).id, projects(:action_controller).id]
    developer.save
    developer.reload
    assert_equal 2, developer.projects.length
    assert_equal projects(:active_record), developer.projects[0] 
    assert_equal projects(:action_controller), developer.projects[1] 
  end

  def test_assign_ids_ignoring_blanks
    developer = Developer.new("name" => "Joe")
    developer.project_ids = [projects(:active_record).id, nil, projects(:action_controller).id, '']
    developer.save
    developer.reload
    assert_equal 2, developer.projects.length
    assert_equal projects(:active_record), developer.projects[0] 
    assert_equal projects(:action_controller), developer.projects[1] 
  end
1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795
  
  def test_select_limited_ids_list
    # Set timestamps
    Developer.transaction do
      Developer.find(:all, :order => 'id').each_with_index do |record, i|
        record.update_attributes(:created_at => 5.years.ago + (i * 5.minutes))
      end
    end
    
    join_base = ActiveRecord::Associations::ClassMethods::JoinDependency::JoinBase.new(Project)
    join_dep  = ActiveRecord::Associations::ClassMethods::JoinDependency.new(join_base, :developers, nil)
1796
    projects  = Project.send(:select_limited_ids_list, {:order => 'developers.created_at'}, join_dep)
1797 1798
    assert_equal "'1', '2'", projects
  end
1799
end