diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index f2feac0..c859fb7 100644 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -1449,11 +1449,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 5d15314..d095891 100644 --- a/activerecord/test/cases/associations/has_one_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_through_associations_test.rb @@ -42,6 +42,18 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase 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") @member.club = new_club