Ensure HABTM relationships produce valid class names (Fixes #17119)

See https://github.com/rails/rails/issues/17119 for the back story.
Ok, thanks. I'll test it locally on JRuby and see what I can come up with if it fails.