Skip to content

Commit

Permalink
belongs_to polymorphic association assignments update the foreign_id …
Browse files Browse the repository at this point in the history
…and foreign_type fields regardless of whether the record being assigned is new or not.

fixes the following scenarios:
* I have validates_inclusion_of on the type field for a polymorphic belongs_to association.  I assign a new record to the model's polymorphic relationship of the proper type.  validation fails because the type field has not been updated.

* I replace the value for a ppolymorphic association to a new record of another class.  The type field still says its the previous class, and the id field points to the previous record as well.
  • Loading branch information
timcharper authored and technoweenie committed May 31, 2008
1 parent f701533 commit aef47dc
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
Expand Up @@ -7,10 +7,8 @@ def replace(record)
else
@target = (AssociationProxy === record ? record.target : record)

unless record.new_record?
@owner[@reflection.primary_key_name] = record.id
@owner[@reflection.options[:foreign_type]] = record.class.base_class.name.to_s
end
@owner[@reflection.primary_key_name] = record.id
@owner[@reflection.options[:foreign_type]] = record.class.base_class.name.to_s

@updated = true
end
Expand Down
Expand Up @@ -12,6 +12,8 @@
require 'models/tag'
require 'models/tagging'
require 'models/comment'
require 'models/sponsor'
require 'models/member'

class BelongsToAssociationsTest < ActiveRecord::TestCase
fixtures :accounts, :companies, :developers, :projects, :topics,
Expand Down Expand Up @@ -381,5 +383,30 @@ def test_cant_save_readonly_association
assert_raise(ActiveRecord::ReadOnlyRecord) { companies(:first_client).readonly_firm.save! }
assert companies(:first_client).readonly_firm.readonly?
end


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

# should update when assigning a new record
sponsor = Sponsor.new
member = Member.new
sponsor.sponsorable = member
assert_equal "Member", sponsor.sponsorable_type
end

def test_polymorphic_assignment_updates_foreign_id_field_for_new_and_saved_records
sponsor = Sponsor.new
saved_member = Member.create
new_member = Member.new

sponsor.sponsorable = saved_member
assert_equal saved_member.id, sponsor.sponsorable_id

sponsor.sponsorable = new_member
assert_equal nil, sponsor.sponsorable_id
end
end

0 comments on commit aef47dc

Please sign in to comment.