Help us understand the problem. What is going on with this article?

Rails 絵文字を登録〜Mysql2::Error: Incorrect string value〜

Railsで作ってるフォームに絵文字を登録しようとして

Mysql2::Error: Incorrect string valueと怒られた。
絵文字の形式が対応してないよーってことらしく、utf8utf8bm4に変換すれば解決するらしかった。

database.yml

utf8になっていたらutf8mb4に変換!

database.yml
default: &default
  adapter: mysql2
  encoding: utf8mb4
  charset: utf8mb4
  collation: utf8mb4_bin
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: root
  password:
  port: <%= ENV['DB_PORT'] || 3306 %>
  reconnect: true

DB

mysqlのなかで

mysql> SHOW VARIABLES like 'char%';
+--------------------------+----------------------------------------------------------+
| Variable_name            | Value                                                    |
+--------------------------+----------------------------------------------------------+
| character_set_client     | utf8mb4                                                  |
| character_set_connection | utf8mb4                                                  |
| character_set_database   | utf8mb4                                                  |
| character_set_filesystem | binary                                                   |
| character_set_results    | utf8mb4                                                  |
| character_set_server     | utf8mb4                                                  |
| character_set_system     | utf8                                                     |
| character_sets_dir       | /usr/local/Cellar/mysql@5.7/5.7.28/share/mysql/charsets/ |
+--------------------------+----------------------------------------------------------+
8 rows in set (0.02 sec)

これはもう変更後なんだけど、変更前はutf8祭りなので

SET character_set_database=utf8mb4;

で↑のようにutf8mb4に変換される

テーブルことにもできるはずなんだけど、何だかうまくいかなかったので全部utf8mb4にかえっちゃった

参考: https://qiita.com/katsuyan/items/0c7ed34d9f8235b8363a

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away