1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

has_one :through should not create a new association when assigned nil [#698 state:resolved]

Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
This commit is contained in:
Daniel Guettler 2009-05-17 14:48:20 +02:00 committed by Pratik Naik
parent a9e8c4b374
commit 25724eede9
2 changed files with 16 additions and 9 deletions

View file

@ -1,31 +1,31 @@
module ActiveRecord
module Associations
class HasOneThroughAssociation < HasManyThroughAssociation
def create_through_record(new_value) #nodoc:
klass = @reflection.through_reflection.klass
current_object = @owner.send(@reflection.through_reflection.name)
if current_object
current_object.update_attributes(construct_join_attributes(new_value))
new_value ? current_object.update_attributes(construct_join_attributes(new_value)) : current_object.destroy
else
@owner.send(@reflection.through_reflection.name, klass.send(:create, construct_join_attributes(new_value)))
@owner.send(@reflection.through_reflection.name, klass.send(:create, construct_join_attributes(new_value))) if new_value
end
end
private
def find(*args)
super(args.merge(:limit => 1))
end
def find_target
super.first
end
def reset_target!
@target = nil
end
end
end
end
end
end

View file

@ -43,7 +43,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