Search code examples
mysqlruby-on-railsrubyutf8mb4

Save utf8mb4 characters in mysql without changing anything in the table or db


I have a utf8mb4 character that needs to be saved in a column in MySQL. All the solutions pointed towards either removing the 4-byte character or changing the collation or charset of my table.

I have also noticed that Rails(ActiveRecord) safely converted 💡 to \U0001F4A1 and stored it in the database. I want to know how ActiveRecord is doing it and how I can do this


Solution

  • Short answer: You cannot do that. If you want to save 4 byte character in mysql you need to use UTF8mb4

    Longer answer: In a hacky way, you can save characters like that with serialization. Say your model is Foo and column where you saving 4 byte character is bar, you will have something like:

    class Foo < ActiveRecord::Base
      serialize :bar
    end
    

    This IS hack though. It will work, but you will need to serialize all the other existing records (otherwise you're asking for trouble).

    Been playing with ideas like that while trying to suppport emojis on legacy UTF8 database and unfortunately, other than opting for UTF8mb4, there's no other good way to go about it.

    Another alternative if you're only interested in dealing with emojis is use something like emojimmy