Mysql2::Error: Incorrect string value

后端 未结 7 1481
青春惊慌失措
青春惊慌失措 2021-01-29 23:30

I have a rails application running on production mode, but all of the sudden this error came up today when a user tried to save a record.



        
7条回答
  •  南笙
    南笙 (楼主)
    2021-01-29 23:56

    I managed to store emojis (which take up 4 bytes) by following this blog post:

    Rails 4, MySQL, and Emoji (Mysql2::Error: Incorrect string value error.)

    You might think that you’re safe inserting most utf8 data in to mysql when you’ve specified that the charset is utf-8. Sadly, however, you’d be wrong. The problem is that the utf8 character set takes up 3 bytes when stored in a VARCHAR column. Emoji characters, on the other hand, take up 4 bytes.

    The solution is in 2 parts:

    Change the encoding of your table and fields:

    ALTER TABLE `[table]` 
      CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin,
    MODIFY [column] VARCHAR(250)
        CHARACTER SET utf8mb4 COLLATE utf8mb4_bin
    

    Tell the mysql2 adapter about it:

    development:
      adapter: mysql2
      database: db
      username: 
      password:
      encoding: utf8mb4
      collation: utf8mb4_unicode_ci
    

    Hope this helps someone!

    Then I had to restart my app and it worked. Please note that some emojis will work without this fix, while some won't:

    • ➡️ Did work
提交回复
热议问题