9
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rails MySQL 絵文字が含まれる文字列を保存する場合の設定

9
Last updated at Posted at 2018-07-02

はじめに

昨今スマホユーザーは絵文字をメチャクチャ使います。
単純にデフォルト設定のまま開発を進めていると
Mysql2::Error: Incorrect string value
と言われてしまうのです。

設定

とにかく重要なのはutf8mb4です。
どうも公式によると、

utf8 という名前の文字セットは、文字あたり最大 3 バイトを使用し、BMP 文字だけを含みます。utf8mb4 文字セットは、文字ごとに最大 4 バイトを使用し、補助文字をサポートします。

ということでデータで絵文字を表現するには4バイト必要になってくるのだと勝手に解釈しています。(調べてないので確かではない)

database.yml

以下を追記します。

database.yml
charset: utf8mb4
encoding: utf8mb4

table.schema

うちではRidgepoleを使っているのでそちらの設定です。
Rails マイグレーションの廃止とRidgepoleの導入・利用方法
マイグレーションを使っている人はそちらの環境に当てはめてください。

table.schema
# -*- mode: ruby -*-
# vi: set ft=ruby :
create_table "tables", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4" do |t|
  t.string "name"
  t.text "message"
  t.datetime "created_at", default: -> { "CURRENT_TIMESTAMP" }, null: false
  t.timestamp "updated_at", default: -> { "CURRENT_TIMESTAMP" }, null: false
end

終わりに

知っていればなんともないことですよねー

ブログで見たい方はこちら
Rails MySQL 絵文字が含まれる文字列を保存する場合の設定

9
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?