From 12ef5c5e8a3525355a48979b4fcece582ddad8b8 Mon Sep 17 00:00:00 2001 From: Daniel Guettler Date: Mon, 26 Jan 2009 20:31:55 -0500 Subject: [PATCH] has_one :through should not try to create new record when nil is passed - if nil is passed to a has_one through association no record is created - if there is an existing record it gets destroyed --- .../associations/has_one_through_association.rb | 2 ++ .../has_one_through_associations_test.rb | 9 ++++++++- 2 files changed, 10 insertions(+), 1 deletions(-) diff --git a/activerecord/lib/active_record/associations/has_one_through_association.rb b/activerecord/lib/active_record/associations/has_one_through_association.rb index 8073eba..f0fb627 100644 --- a/activerecord/lib/active_record/associations/has_one_through_association.rb +++ b/activerecord/lib/active_record/associations/has_one_through_association.rb @@ -8,8 +8,10 @@ module ActiveRecord current_object = @owner.send(@reflection.through_reflection.name) if current_object + (current_object.destroy and return nil) unless new_value current_object.update_attributes(construct_join_attributes(new_value)) else + return nil unless new_value @owner.send(@reflection.through_reflection.name, klass.send(:create, construct_join_attributes(new_value))) end end 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 7d418de..222099c 100644 --- a/activerecord/test/cases/associations/has_one_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_through_associations_test.rb @@ -42,7 +42,14 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase @member.reload end end - + + def test_set_record_to_nil_should_delete_association + @member.club = nil + @member.reload + assert_equal nil, @member.current_membership + assert_nil @member.club + end + def test_has_one_through_polymorphic assert_equal clubs(:moustache_club), @member.sponsor_club end -- 1.5.6