From 5a9590c6cbbb4ac26a81ae37088a38778cb12748 Mon Sep 17 00:00:00 2001 From: James Dabbs Date: Sat, 13 Jun 2015 18:36:06 -0400 Subject: Fix `undefined method uncached` for polymorphic belongs_to #20426 Unitialized polymorphic `belongs_to` associations raise an error while attempting to reload, as they attempt to make an uncached reload, but don't have a klass to fetch uncachedly. In this case, `loaded?` should be `false` anyway. --- activerecord/lib/active_record/associations/singular_association.rb | 2 +- activerecord/test/cases/associations/belongs_to_associations_test.rb | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/associations/singular_association.rb b/activerecord/lib/active_record/associations/singular_association.rb index 58d0f7d65d..bec9505bd2 100644 --- a/activerecord/lib/active_record/associations/singular_association.rb +++ b/activerecord/lib/active_record/associations/singular_association.rb @@ -3,7 +3,7 @@ module ActiveRecord class SingularAssociation < Association #:nodoc: # Implements the reader method, e.g. foo.bar for Foo.has_one :bar def reader(force_reload = false) - if force_reload + if force_reload && klass klass.uncached { reload } elsif !loaded? || stale_target? reload diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index ba90c61d65..f5d2fe151b 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -288,6 +288,7 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase def test_polymorphic_association_class sponsor = Sponsor.new assert_nil sponsor.association(:sponsorable).send(:klass) + assert_nil sponsor.sponsorable(force_reload: true) sponsor.sponsorable_type = '' # the column doesn't have to be declared NOT NULL assert_nil sponsor.association(:sponsorable).send(:klass) -- cgit v1.2.3