Skip to content

Commit

Permalink
Fix two has_one :through errors
Browse files Browse the repository at this point in the history
* Set the association target on assignment;
* Reset target to nil on reset, rather than empty array.

Signed-off-by: Michael Koziarski <michael@koziarski.com>
[#895 state:committed]
  • Loading branch information
pivotal authored and NZKoz committed Aug 27, 2008
1 parent b4d13a9 commit e710902
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 3 deletions.
5 changes: 2 additions & 3 deletions activerecord/lib/active_record/associations.rb
Expand Up @@ -1111,10 +1111,9 @@ def association_accessor_methods(reflection, association_proxy_class)
association.create_through_record(new_value) association.create_through_record(new_value)
self.send(reflection.name, new_value) self.send(reflection.name, new_value)
else else
association.replace(new_value) association.replace(new_value)
instance_variable_set(ivar, new_value.nil? ? nil : association)
end end

instance_variable_set(ivar, new_value.nil? ? nil : association)
end end


define_method("set_#{reflection.name}_target") do |target| define_method("set_#{reflection.name}_target") do |target|
Expand Down
Expand Up @@ -22,6 +22,10 @@ def find(*args)


def find_target def find_target
super.first super.first
end

def reset_target!
@target = nil
end end
end end
end end
Expand Down
Expand Up @@ -101,4 +101,13 @@ def test_has_one_through_nonpreload_eager_loading_through_polymorphic_with_more_
assert_equal clubs(:crazy_club), members[0].sponsor_club assert_equal clubs(:crazy_club), members[0].sponsor_club
end end


def test_uninitialized_has_one_through_should_return_nil_for_unsaved_record
assert_nil Member.new.club
end

def test_assigning_association_correctly_assigns_target
new_member = Member.create(:name => "Chris")
new_member.club = new_club = Club.create(:name => "LRUG")
assert_equal new_club, new_member.club.target
end
end end

0 comments on commit e710902

Please sign in to comment.