Skip to content
This repository
Browse code

Allow ho:through#build when the owner is a new record [#1749 state:re…

…solved]

Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
  • Loading branch information...
commit a0f69722be00cd546558b067054e9e7ae2564274 1 parent 0472839
Tristan Dunn tristandunn authored lifo committed
12 activerecord/lib/active_record/associations/has_one_through_association.rb
@@ -18,9 +18,15 @@ def create_through_record(new_value) #nodoc:
18 18 current_object = @owner.send(@reflection.through_reflection.name)
19 19
20 20 if current_object
21   - new_value ? current_object.update_attributes(construct_join_attributes(new_value)) : current_object.destroy
22   - else
23   - @owner.send(@reflection.through_reflection.name, klass.send(:create, construct_join_attributes(new_value))) if new_value
  21 + new_value ? current_object.update_attributes(construct_join_attributes(new_value)) : current_object.destroy
  22 + elsif new_value
  23 + if @owner.new_record?
  24 + self.target = new_value
  25 + through_association = @owner.send(:association_instance_get, @reflection.through_reflection.name)
  26 + through_association.build(construct_join_attributes(new_value))
  27 + else
  28 + @owner.send(@reflection.through_reflection.name, klass.create(construct_join_attributes(new_value)))
  29 + end
24 30 end
25 31 end
26 32
10 activerecord/test/cases/associations/has_one_through_associations_test.rb
@@ -28,6 +28,16 @@ def test_creating_association_creates_through_record
28 28 assert_not_nil new_member.current_membership
29 29 assert_not_nil new_member.club
30 30 end
  31 +
  32 + def test_creating_association_builds_through_record_for_new
  33 + new_member = Member.new(:name => "Jane")
  34 + new_member.club = clubs(:moustache_club)
  35 + assert new_member.current_membership
  36 + assert_equal clubs(:moustache_club), new_member.current_membership.club
  37 + assert_equal clubs(:moustache_club), new_member.club
  38 + assert new_member.save
  39 + assert_equal clubs(:moustache_club), new_member.club
  40 + end
31 41
32 42 def test_replace_target_record
33 43 new_club = Club.create(:name => "Marx Bros")

0 comments on commit a0f6972

Please sign in to comment.
Something went wrong with that request. Please try again.