From 85ab68c69dd7e172b2c74d2c4e3d6f268ca1b9fa Mon Sep 17 00:00:00 2001 From: Tanel Suurhans Date: Fri, 30 Apr 2010 12:10:21 +0300 Subject: [PATCH] Fix issues with polymorphic belongs_to blank parameters [#4503:resolved] --- .../belongs_to_polymorphic_association.rb | 4 +- .../associations/belongs_to_associations_test.rb | 21 +++++++++++++++++++- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb b/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb index f6edd63..b8c68fe 100644 --- a/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb +++ b/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb @@ -2,7 +2,7 @@ module ActiveRecord module Associations class BelongsToPolymorphicAssociation < AssociationProxy #:nodoc: def replace(record) - if record.nil? + if record.blank? @target = @owner[@reflection.primary_key_name] = @owner[@reflection.options[:foreign_type]] = nil else @target = (AssociationProxy === record ? record.target : record) @@ -70,7 +70,7 @@ module ActiveRecord end def association_class - @owner[@reflection.options[:foreign_type]] ? @owner[@reflection.options[:foreign_type]].constantize : nil + @owner[@reflection.options[:foreign_type]].present? ? @owner[@reflection.options[:foreign_type]].constantize : nil end end end diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index ab0edee..60ef05d 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -357,7 +357,7 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase 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 @@ -410,6 +410,25 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase assert_equal nil, essay.writer_id end + def test_polymorphic_assigment_with_blank_object_and_attributes + sponsor = Sponsor.new + + assert_nothing_raised do + sponsor.sponsorable = "" + end + + assert_equal nil, sponsor.sponsorable + + sponsor.sponsorable_id = "" + sponsor.sponsorable_type = "" + sponsor.save + sponsor.reload + + assert_nothing_raised do + sponsor.sponsorable + end + end + def test_belongs_to_proxy_should_not_respond_to_private_methods assert_raise(NoMethodError) { companies(:first_firm).private_method } assert_raise(NoMethodError) { companies(:second_client).firm.private_method } -- 1.7.0.5