belongs_to_associations_test.rb 19.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
require "cases/helper"
require 'models/developer'
require 'models/project'
require 'models/company'
require 'models/topic'
require 'models/reply'
require 'models/computer'
require 'models/post'
require 'models/author'
require 'models/tag'
require 'models/tagging'
require 'models/comment'
13 14
require 'models/sponsor'
require 'models/member'
15
require 'models/essay'
16 17 18

class BelongsToAssociationsTest < ActiveRecord::TestCase
  fixtures :accounts, :companies, :developers, :projects, :topics,
19
           :developers_projects, :computers, :authors, :author_addresses,
20
           :posts, :tags, :taggings, :comments, :sponsors, :members
21 22 23 24

  def test_belongs_to
    Client.find(3).firm.name
    assert_equal companies(:first_firm).name, Client.find(3).firm.name
25
    assert_not_nil Client.find(3).firm, "Microsoft should have a firm"
26 27
  end

28 29 30 31 32
  def test_belongs_to_with_primary_key
    client = Client.create(:name => "Primary key client", :firm_name => companies(:first_firm).name)
    assert_equal companies(:first_firm).name, client.firm_with_primary_key.name
  end

33 34
  def test_belongs_to_with_primary_key_joins_on_correct_column
    sql = Client.joins(:firm_with_primary_key).to_sql
B
Brian Lopez 已提交
35
    if current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter)
36 37
      assert_no_match(/`firm_with_primary_keys_companies`\.`id`/, sql)
      assert_match(/`firm_with_primary_keys_companies`\.`name`/, sql)
38 39 40 41
    elsif current_adapter?(:OracleAdapter)
      # on Oracle aliases are truncated to 30 characters and are quoted in uppercase
      assert_no_match(/"firm_with_primary_keys_compani"\."id"/i, sql)
      assert_match(/"firm_with_primary_keys_compani"\."name"/i, sql)
E
Emilio Tagua 已提交
42
    else
43 44
      assert_no_match(/"firm_with_primary_keys_companies"\."id"/, sql)
      assert_match(/"firm_with_primary_keys_companies"\."name"/, sql)
E
Emilio Tagua 已提交
45
    end
46 47
  end

48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
  def test_proxy_assignment
    account = Account.find(1)
    assert_nothing_raised { account.firm = account.firm }
  end

  def test_triple_equality
    assert Client.find(3).firm === Firm
    assert Firm === Client.find(3).firm
  end

  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

70 71 72 73 74 75 76
  def test_natural_assignment_with_primary_key
    apple = Firm.create("name" => "Apple")
    citibank = Client.create("name" => "Primary key client")
    citibank.firm_with_primary_key = apple
    assert_equal apple.name, citibank.firm_name
  end

77
  def test_eager_loading_with_primary_key
A
Aaron Patterson 已提交
78 79
    Firm.create("name" => "Apple")
    Client.create("name" => "Citibank", :firm_name => "Apple")
80
    citibank_result = Client.find(:first, :conditions => {:name => "Citibank"}, :include => :firm_with_primary_key)
81
    assert citibank_result.association_cache.key?(:firm_with_primary_key)
82 83
  end

84 85 86 87
  def test_eager_loading_with_primary_key_as_symbol
    Firm.create("name" => "Apple")
    Client.create("name" => "Citibank", :firm_name => "Apple")
    citibank_result = Client.find(:first, :conditions => {:name => "Citibank"}, :include => :firm_with_primary_key_symbols)
88
    assert citibank_result.association_cache.key?(:firm_with_primary_key_symbols)
89 90
  end

91 92 93 94 95 96 97 98 99
  def test_creating_the_belonging_object
    citibank = Account.create("credit_limit" => 10)
    apple    = citibank.create_firm("name" => "Apple")
    assert_equal apple, citibank.firm
    citibank.save
    citibank.reload
    assert_equal apple, citibank.firm
  end

100 101 102 103 104 105 106 107 108
  def test_creating_the_belonging_object_with_primary_key
    client = Client.create(:name => "Primary key client")
    apple  = client.create_firm_with_primary_key("name" => "Apple")
    assert_equal apple, client.firm_with_primary_key
    client.save
    client.reload
    assert_equal apple, client.firm_with_primary_key
  end

109 110 111 112 113 114 115
  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

116 117 118 119 120 121 122
  def test_building_the_belonging_object_with_primary_key
    client = Client.create(:name => "Primary key client")
    apple  = client.build_firm_with_primary_key("name" => "Apple")
    client.save
    assert_equal apple.name, client.firm_name
  end

123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
  def test_create!
    client  = Client.create!(:name => "Jimmy")
    account = client.create_account!(:credit_limit => 10)
    assert_equal account, client.account
    assert account.persisted?
    client.save
    client.reload
    assert_equal account, client.account
  end

  def test_failing_create!
    client  = Client.create!(:name => "Jimmy")
    assert_raise(ActiveRecord::RecordInvalid) { client.create_account! }
    assert_not_nil client.account
    assert client.account.new_record?
  end

140 141 142 143 144 145 146 147
  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

148 149 150 151 152 153 154 155
  def test_natural_assignment_to_nil_with_primary_key
    client = Client.create(:name => "Primary key client", :firm_name => companies(:first_firm).name)
    client.firm_with_primary_key = nil
    client.save
    assert_nil client.firm_with_primary_key(true)
    assert_nil client.client_of
  end

156 157 158 159 160 161 162 163 164 165
  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

166 167 168 169 170 171 172 173 174
  def test_with_polymorphic_and_condition
    sponsor = Sponsor.create
    member = Member.create :name => "Bert"
    sponsor.sponsorable = member

    assert_equal member, sponsor.sponsorable
    assert_nil sponsor.sponsorable_with_conditions
  end

175 176 177 178 179
  def test_with_select
    assert_equal Company.find(2).firm_with_select.attributes.size, 1
    assert_equal Company.find(2, :include => :firm_with_select ).firm_with_select.attributes.size, 1
  end

180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
  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

  def test_belongs_to_counter_with_assigning_nil
    p = Post.find(1)
    c = Comment.find(1)

    assert_equal p.id, c.post_id
    assert_equal 2, Post.find(p.id).comments.size

    c.post = nil

    assert_equal 1, Post.find(p.id).comments.size
  end

203 204 205 206 207 208 209 210 211
  def test_belongs_to_with_primary_key_counter
    debate  = Topic.create("title" => "debate")
    debate2 = Topic.create("title" => "debate2")
    reply   = Reply.create("title" => "blah!", "content" => "world around!", "parent_title" => "debate")

    assert_equal 1, debate.reload.replies_count
    assert_equal 0, debate2.reload.replies_count

    reply.topic_with_primary_key = debate2
212

213 214
    assert_equal 0, debate.reload.replies_count
    assert_equal 1, debate2.reload.replies_count
215 216 217

    reply.topic_with_primary_key = nil

218 219
    assert_equal 0, debate.reload.replies_count
    assert_equal 0, debate2.reload.replies_count
220 221
  end

222 223 224 225 226 227 228 229 230 231 232 233
  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)

234 235 236 237
    assert_no_queries do
      r1.topic = t2
    end

238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
    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

258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
  def test_belongs_to_reassign_with_namespaced_models_and_counters
    t1 = Web::Topic.create("title" => "t1")
    t2 = Web::Topic.create("title" => "t2")
    r1 = Web::Reply.new("title" => "r1", "content" => "r1")
    r1.topic = t1

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

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

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

275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
  def test_belongs_to_counter_after_save
    topic = Topic.create!(:title => "monday night")
    topic.replies.create!(:title => "re: monday night", :content => "football")
    assert_equal 1, Topic.find(topic.id)[:replies_count]

    topic.save!
    assert_equal 1, Topic.find(topic.id)[:replies_count]
  end

  def test_belongs_to_counter_after_update_attributes
    topic = Topic.create!(:title => "37s")
    topic.replies.create!(:title => "re: 37s", :content => "rails")
    assert_equal 1, Topic.find(topic.id)[:replies_count]

    topic.update_attributes(:title => "37signals")
    assert_equal 1, Topic.find(topic.id)[:replies_count]
  end

  def test_assignment_before_child_saved
    final_cut = Client.new("name" => "Final Cut")
    firm = Firm.find(1)
    final_cut.firm = firm
297
    assert !final_cut.persisted?
298
    assert final_cut.save
299 300
    assert final_cut.persisted?
    assert firm.persisted?
301 302 303 304
    assert_equal firm, final_cut.firm
    assert_equal firm, final_cut.firm(true)
  end

305 306 307 308
  def test_assignment_before_child_saved_with_primary_key
    final_cut = Client.new("name" => "Final Cut")
    firm = Firm.find(1)
    final_cut.firm_with_primary_key = firm
309
    assert !final_cut.persisted?
310
    assert final_cut.save
311 312
    assert final_cut.persisted?
    assert firm.persisted?
313 314 315 316
    assert_equal firm, final_cut.firm_with_primary_key
    assert_equal firm, final_cut.firm_with_primary_key(true)
  end

317 318
  def test_new_record_with_foreign_key_but_no_object
    c = Client.new("firm_id" => 1)
319 320
    # sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first
    assert_equal Firm.find(:first, :order => "id"), c.firm_with_basic_id
321 322
  end

323 324 325 326
  def test_setting_foreign_key_after_nil_target_loaded
    client = Client.new
    client.firm_with_basic_id
    client.firm_id = 1
327

328 329 330 331 332 333 334 335 336 337
    assert_equal companies(:first_firm), client.firm_with_basic_id
  end

  def test_polymorphic_setting_foreign_key_after_nil_target_loaded
    sponsor = Sponsor.new
    sponsor.sponsorable
    sponsor.sponsorable_id = 1
    sponsor.sponsorable_type = "Member"

    assert_equal members(:groucho), sponsor.sponsorable
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
  end

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

  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]
    assert_equal 1, topic.replies.size

    topic[:replies_count] = 15
    assert_equal 15, topic.replies.size
  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]
    assert_equal 1, reply.replies.size

    reply[:replies_count] = 17
    assert_equal 17, reply.replies.size
  end

  def test_association_assignment_sticks
    post = Post.find(:first)

    author1, author2 = Author.find(:all, :limit => 2)
    assert_not_nil author1
    assert_not_nil author2

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

  def test_cant_save_readonly_association
    assert_raise(ActiveRecord::ReadOnlyRecord) { companies(:first_client).readonly_firm.save! }
    assert companies(:first_client).readonly_firm.readonly?
  end
398

399 400 401 402 403 404
  def test_polymorphic_assignment_foreign_type_field_updating
    # should update when assigning a saved record
    sponsor = Sponsor.new
    member = Member.create
    sponsor.sponsorable = member
    assert_equal "Member", sponsor.sponsorable_type
405

406 407 408 409 410 411
    # should update when assigning a new record
    sponsor = Sponsor.new
    member = Member.new
    sponsor.sponsorable = member
    assert_equal "Member", sponsor.sponsorable_type
  end
412 413 414 415 416 417 418 419 420 421 422 423 424 425

  def test_polymorphic_assignment_with_primary_key_foreign_type_field_updating
    # should update when assigning a saved record
    essay = Essay.new
    writer = Author.create(:name => "David")
    essay.writer = writer
    assert_equal "Author", essay.writer_type

    # should update when assigning a new record
    essay = Essay.new
    writer = Author.new
    essay.writer = writer
    assert_equal "Author", essay.writer_type
  end
426

427 428 429 430
  def test_polymorphic_assignment_updates_foreign_id_field_for_new_and_saved_records
    sponsor = Sponsor.new
    saved_member = Member.create
    new_member = Member.new
431

432 433
    sponsor.sponsorable = saved_member
    assert_equal saved_member.id, sponsor.sponsorable_id
434

435
    sponsor.sponsorable = new_member
436
    assert_nil sponsor.sponsorable_id
437
  end
438

439 440 441 442 443 444 445 446 447 448 449 450
  def test_assignment_updates_foreign_id_field_for_new_and_saved_records
    client = Client.new
    saved_firm = Firm.create :name => "Saved"
    new_firm = Firm.new

    client.firm = saved_firm
    assert_equal saved_firm.id, client.client_of

    client.firm = new_firm
    assert_nil client.client_of
  end

451 452 453 454 455 456 457 458 459
  def test_polymorphic_assignment_with_primary_key_updates_foreign_id_field_for_new_and_saved_records
    essay = Essay.new
    saved_writer = Author.create(:name => "David")
    new_writer = Author.new

    essay.writer = saved_writer
    assert_equal saved_writer.name, essay.writer_id

    essay.writer = new_writer
460
    assert_nil essay.writer_id
461 462
  end

463
  def test_belongs_to_proxy_should_not_respond_to_private_methods
464 465
    assert_raise(NoMethodError) { companies(:first_firm).private_method }
    assert_raise(NoMethodError) { companies(:second_client).firm.private_method }
466 467 468 469 470 471
  end

  def test_belongs_to_proxy_should_respond_to_private_methods_via_send
    companies(:first_firm).send(:private_method)
    companies(:second_client).firm.send(:private_method)
  end
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487

  def test_save_of_record_with_loaded_belongs_to
    @account = companies(:first_firm).account

    assert_nothing_raised do
      Account.find(@account.id).save!
      Account.find(@account.id, :include => :firm).save!
    end

    @account.firm.delete

    assert_nothing_raised do
      Account.find(@account.id).save!
      Account.find(@account.id, :include => :firm).save!
    end
  end
488 489 490 491 492 493 494 495 496 497 498 499 500 501

  def test_dependent_delete_and_destroy_with_belongs_to
    author_address = author_addresses(:david_address)
    author_address_extra = author_addresses(:david_address_extra)
    assert_equal [], AuthorAddress.destroyed_author_address_ids

    assert_difference "AuthorAddress.count", -2 do
      authors(:david).destroy
    end

    assert_equal [], AuthorAddress.find_all_by_id([author_address.id, author_address_extra.id])
    assert_equal [author_address.id], AuthorAddress.destroyed_author_address_ids
  end

502
  def test_invalid_belongs_to_dependent_option_nullify_raises_exception
503 504 505 506
    assert_raise ArgumentError do
      Author.belongs_to :special_author_address, :dependent => :nullify
    end
  end
E
Emilio Tagua 已提交
507

508 509 510 511 512
  def test_invalid_belongs_to_dependent_option_restrict_raises_exception
    assert_raise ArgumentError do
      Author.belongs_to :special_author_address, :dependent => :restrict
    end
  end
513 514 515 516 517

  def test_attributes_are_being_set_when_initialized_from_belongs_to_association_with_where_clause
    new_firm = accounts(:signals37).build_firm(:name => 'Apple')
    assert_equal new_firm.name, "Apple"
  end
518 519

  def test_reassigning_the_parent_id_updates_the_object
520
    client = companies(:second_client)
521

522 523 524 525
    client.firm
    client.firm_with_condition
    firm_proxy                = client.send(:association_instance_get, :firm)
    firm_with_condition_proxy = client.send(:association_instance_get, :firm_with_condition)
526

527 528 529 530 531 532 533 534 535 536 537
    assert !firm_proxy.stale_target?
    assert !firm_with_condition_proxy.stale_target?
    assert_equal companies(:first_firm), client.firm
    assert_equal companies(:first_firm), client.firm_with_condition

    client.client_of = companies(:another_firm).id

    assert firm_proxy.stale_target?
    assert firm_with_condition_proxy.stale_target?
    assert_equal companies(:another_firm), client.firm
    assert_equal companies(:another_firm), client.firm_with_condition
538 539 540
  end

  def test_polymorphic_reassignment_of_associated_id_updates_the_object
541 542 543 544 545 546 547
    sponsor = sponsors(:moustache_club_sponsor_for_groucho)

    sponsor.sponsorable
    proxy = sponsor.send(:association_instance_get, :sponsorable)

    assert !proxy.stale_target?
    assert_equal members(:groucho), sponsor.sponsorable
548

549
    sponsor.sponsorable_id = members(:some_other_guy).id
550

551 552
    assert proxy.stale_target?
    assert_equal members(:some_other_guy), sponsor.sponsorable
553 554 555
  end

  def test_polymorphic_reassignment_of_associated_type_updates_the_object
556
    sponsor = sponsors(:moustache_club_sponsor_for_groucho)
557

558 559
    sponsor.sponsorable
    proxy = sponsor.send(:association_instance_get, :sponsorable)
560

561 562 563 564
    assert !proxy.stale_target?
    assert_equal members(:groucho), sponsor.sponsorable

    sponsor.sponsorable_type = 'Firm'
565

566 567 568
    assert proxy.stale_target?
    assert_equal companies(:first_firm), sponsor.sponsorable
  end
569 570 571 572 573 574 575 576 577 578 579

  def test_reloading_association_with_key_change
    client = companies(:second_client)
    firm = client.firm # note this is a proxy object

    client.firm = companies(:another_firm)
    assert_equal companies(:another_firm), firm.reload

    client.client_of = companies(:first_firm).id
    assert_equal companies(:first_firm), firm.reload
  end
580 581 582 583 584 585 586 587 588 589 590 591

  def test_polymorphic_counter_cache
    tagging = taggings(:welcome_general)
    post    = posts(:welcome)
    comment = comments(:greetings)

    assert_difference 'post.reload.taggings_count', -1 do
      assert_difference 'comment.reload.taggings_count', +1 do
        tagging.taggable = comment
      end
    end
  end
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610

  def test_polymorphic_with_custom_foreign_type
    sponsor = sponsors(:moustache_club_sponsor_for_groucho)
    groucho = members(:groucho)
    other   = members(:some_other_guy)

    assert_equal groucho, sponsor.sponsorable
    assert_equal groucho, sponsor.thing

    sponsor.thing = other

    assert_equal other, sponsor.sponsorable
    assert_equal other, sponsor.thing

    sponsor.sponsorable = groucho

    assert_equal groucho, sponsor.sponsorable
    assert_equal groucho, sponsor.thing
  end
611
end