Backport Rails 4.0.10 compatability to 4-0-stable branch

This fix is already present in master, but only for Rails 4.1 and up. See https://github.com/rails/rails/pull/16170