A user is using an emoticon and it is erroring out my app. How can I get check if the string contains an emoticon and remove only the emoticon?
Message.create(user: @user, ticket: @ticket, text: "\r\nIm done with this bug! \u{1f431}!\r\n")
ActiveRecord::StatementInvalid: Mysql2::Error: Incorrect string value: 'x90\xB1!\x0D
This is occuring because your database doesnt allow for utf8mb4 so you need to check for both and return the text. I would do the check as a callback and only if the text field has changed in order to reduce the number of times the callback is called.
before_save :ensure_utf8, if: :text_changed?
def ensure_utf8
if self.text
self.text = self.text.encode( Encoding.find('UTF-8'), { invalid: :replace, undef: :replace, replace: '' } )
self.text = self.text.each_char.select { |c| c.bytes.first < 240 }.join('')
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With