PR #5219 backported to 3-2

This is the 3-2 patch that mimics https://github.com/rails/rails/pull/5219.