rails/rails — pull request #16636 by willbryant (2014-08-22 11:52:06+00:00)
Title: Fix setting a polymorphic association's attributes to nil and saving, if that association had been non-nil and loaded

This raised a nil deref, because the stale_state test returned true (the target was no longer valid) and so #find_target called #scope, which ran klass.all - which failed because #klass is now nil.

This only happened if saving the record holding this polymorphic association, as opposed to say referencing the association, because the latter is implemented by the SingularAssociation#reader method which called #reload if the target was stale. This patch does something similar, but a bit less radical (calling reset).

(Note that the other cases are protected by #find_target?)

This patch also applies cleanly to 4-1-stable and 4-0-stable, where the problem was first introduced.