From ca9ee584a72351ad43da0e68f130366d6c41920b Mon Sep 17 00:00:00 2001 From: David J. Hamilton Date: Fri, 16 Jul 2010 16:45:48 -0700 Subject: [PATCH] Patch for 5137. association accessor for :through associations failed to set association when :through a belongs_to association. --- activerecord/lib/active_record/associations.rb | 8 ++++---- .../has_one_through_associations_test.rb | 12 ++++++++++++ 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index d67df64..758af20 100644 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -1361,11 +1361,11 @@ module ActiveRecord if association.nil? || force_reload association = association_proxy_class.new(self, reflection) retval = force_reload ? reflection.klass.uncached { association.reload } : association.reload - if retval.nil? and association_proxy_class == BelongsToAssociation - association_instance_set(reflection.name, nil) - return nil - end association_instance_set(reflection.name, association) + elsif reflection.belongs_to? && self.class.column_names.include?(reflection.primary_key_name) + key_changed = send("#{reflection.primary_key_name}_changed?") + key = read_attribute(reflection.primary_key_name) + association.reload if key_changed && (key.nil? ^ association.target.nil?) end association.target.nil? ? nil : association diff --git a/activerecord/test/cases/associations/has_one_through_associations_test.rb b/activerecord/test/cases/associations/has_one_through_associations_test.rb index 3fcd150..c120beb 100644 --- a/activerecord/test/cases/associations/has_one_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_through_associations_test.rb @@ -41,6 +41,18 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase assert new_member.save assert_equal clubs(:moustache_club), new_member.club end + + def test_creating_association_builds_through_record_for_new_through_belongs_to + new_minivan = Minivan.new + assert_nothing_raised do + new_minivan.dashboard = dashboards( :cool_first ) + end + assert new_minivan.speedometer + assert_equal dashboards( :cool_first ), new_minivan.speedometer.dashboard + assert_equal dashboards( :cool_first ), new_minivan.dashboard + assert new_minivan.save + assert_equal dashboards( :cool_first ), new_minivan.dashboard + end def test_replace_target_record new_club = Club.create(:name => "Marx Bros") -- 1.7.1.1.dirty