Skip to content

Commit

Permalink
Provide a slightly more robust we_can_set_the_inverse_on_this? method…
Browse files Browse the repository at this point in the history
… for polymorphic belongs_to associations. [#3520 state:resolved]

Also add a new test for polymorphic belongs_to that test direct accessor assignment, not just .replace assignment.

Signed-off-by: Eloy Duran <eloy.de.enige@gmail.com>
  • Loading branch information
h-lame authored and alloy committed Dec 28, 2009
1 parent cca75ca commit 603b28c
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
Expand Up @@ -27,7 +27,12 @@ def updated?
# NOTE - for now, we're only supporting inverse setting from belongs_to back onto
# has_one associations.
def we_can_set_the_inverse_on_this?(record)
@reflection.has_inverse? && @reflection.polymorphic_inverse_of(record.class).macro == :has_one
if @reflection.has_inverse?
inverse_association = @reflection.polymorphic_inverse_of(record.class)
inverse_association && inverse_association.macro == :has_one
else
false
end
end

def set_inverse_instance(record, instance)
Expand All @@ -52,7 +57,7 @@ def find_target
else
association_class.find(@owner[@reflection.primary_key_name], :select => @reflection.options[:select], :include => @reflection.options[:include])
end
set_inverse_instance(target, @owner) if target
set_inverse_instance(target, @owner)
target
end

Expand Down
Expand Up @@ -480,7 +480,22 @@ def test_eager_loaded_child_instance_should_be_shared_with_parent_on_find
assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same after changes to parent-owned instance"
end

def test_child_instance_should_be_shared_with_replaced_parent
def test_child_instance_should_be_shared_with_replaced_via_accessor_parent
face = faces(:confused)
old_man = face.polymorphic_man
new_man = Man.new

assert_not_nil face.polymorphic_man
face.polymorphic_man = new_man

assert_equal face.description, new_man.polymorphic_face.description, "Description of face should be the same before changes to parent instance"
face.description = 'Bongo'
assert_equal face.description, new_man.polymorphic_face.description, "Description of face should be the same after changes to parent instance"
new_man.polymorphic_face.description = 'Mungo'
assert_equal face.description, new_man.polymorphic_face.description, "Description of face should be the same after changes to replaced-parent-owned instance"
end

def test_child_instance_should_be_shared_with_replaced_via_method_parent
face = faces(:confused)
old_man = face.polymorphic_man
new_man = Man.new
Expand Down

0 comments on commit 603b28c

Please sign in to comment.