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:
parent
a9e8c4b374
commit
25724eede9
2 changed files with 16 additions and 9 deletions
|
@ -1,31 +1,31 @@
|
||||||
module ActiveRecord
|
module ActiveRecord
|
||||||
module Associations
|
module Associations
|
||||||
class HasOneThroughAssociation < HasManyThroughAssociation
|
class HasOneThroughAssociation < HasManyThroughAssociation
|
||||||
|
|
||||||
def create_through_record(new_value) #nodoc:
|
def create_through_record(new_value) #nodoc:
|
||||||
klass = @reflection.through_reflection.klass
|
klass = @reflection.through_reflection.klass
|
||||||
|
|
||||||
current_object = @owner.send(@reflection.through_reflection.name)
|
current_object = @owner.send(@reflection.through_reflection.name)
|
||||||
|
|
||||||
if current_object
|
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
|
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
|
||||||
end
|
end
|
||||||
|
|
||||||
private
|
private
|
||||||
def find(*args)
|
def find(*args)
|
||||||
super(args.merge(:limit => 1))
|
super(args.merge(:limit => 1))
|
||||||
end
|
end
|
||||||
|
|
||||||
def find_target
|
def find_target
|
||||||
super.first
|
super.first
|
||||||
end
|
end
|
||||||
|
|
||||||
def reset_target!
|
def reset_target!
|
||||||
@target = nil
|
@target = nil
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
@ -43,7 +43,14 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
|
||||||
@member.reload
|
@member.reload
|
||||||
end
|
end
|
||||||
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
|
def test_has_one_through_polymorphic
|
||||||
assert_equal clubs(:moustache_club), @member.sponsor_club
|
assert_equal clubs(:moustache_club), @member.sponsor_club
|
||||||
end
|
end
|
||||||
|
|
Loading…
Reference in a new issue