Skip to content

Commit

Permalink
Reload through_record that has been destroyed in `create_through_re…
Browse files Browse the repository at this point in the history
…cord`

This is an alternative of #27714.

If `has_one :through` association has set `nil`, `through_record` is
destroyed but still remain loaded target in `through_proxy` until
`reload` or `reset` explicitly.

If `through_proxy` is not reset (remain destroyed (frozen) target),
setting new record causes `RuntimeError: Can't modify frozen hash`.

To prevent `RuntimeError`, should reload `through_record` that has been
destroyed in `create_through_record`.
  • Loading branch information
kamipo committed Jan 29, 2017
1 parent 6a1c021 commit e09da8b
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 0 deletions.
Expand Up @@ -22,6 +22,10 @@ def create_through_record(record)
elsif record
attributes = construct_join_attributes(record)

if through_record && through_record.destroyed?
through_record = through_proxy.tap(&:reload).target
end

if through_record
through_record.update(attributes)
elsif owner.new_record?
Expand Down
Expand Up @@ -86,6 +86,13 @@ def test_set_record_to_nil_should_delete_association
assert_nil @member.club
end

def test_set_record_after_delete_association
@member.club = nil
@member.club = clubs(:moustache_club)
@member.reload
assert_equal clubs(:moustache_club), @member.club
end

def test_has_one_through_polymorphic
assert_equal clubs(:moustache_club), @member.sponsor_club
end
Expand Down

0 comments on commit e09da8b

Please sign in to comment.