Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

belongs_to polymorphic association assignments update the foreign_id …

…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.

[#191 state:closed]
  • Loading branch information...
commit 0580b31b36c0f7dd1a0f8bdd1b1806e3bd65b22d 1 parent f701533
@timcharper timcharper authored technoweenie committed
View
6 activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb
@@ -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
View
29 activerecord/test/cases/associations/belongs_to_associations_test.rb
@@ -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,
@@ -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
Please sign in to comment.
Something went wrong with that request. Please try again.