I am having a problem with users copying and pasting input which leads to non-printable characters preventing MySQL from saving records. Here's the error:
Mysql2::Error: Incorrect string value: '\xE2\x80\x8B\xE2\x80\x8B...' for column 'address' at row 1
I don't find the existing answers to similar questions satisfactory, as they seem to all require me to change the database to accept these unicode characters. But I don't want to be saving these characters! I'd much rather strip them out and keep valid ASCII characters.
What's the best/preferred way to do this? So far I have come across the following methods:
"offending string".encode(Encoding.find('ASCII'), {invalid: :replace, undef: :replace, replace: "", universal_newline: true})
This seems to work most of the time, except to compensate for nil fields I have to use a ternary expression on each field. Serious code smell!
Then there's this:
.gsub(/(\W|\d)/, "")
Which does part of what I want, but it also removes characters like quotes.
I'd prefer a setting that I can change rather than tack on method calls to my params.