LoginSignup
1
0

More than 5 years have passed since last update.

Railsでutf8mb4設定

Posted at

Railsで公開APIからデータを収集し、MySQLに保存するプログラムを書いて動かした所、ActiveRecordエラー発生。
MySQLのutf8mb4対応の問題だった。

環境

  • Ruby 2.5.1
  • Rails 5.2
  • MySQL 5.7

エラー

ActiveRecord::StatementInvalid (Mysql2::Error: Incorrect string value: '\xF0\x9F\xA4\x94 \x0A...' for column 'xxxx' at row 1: INSERT INTO ...

原因

Insertするデータに絵文字が含まれていた。
自分で入力していない、APIから収集したデータだったので、発見に手間取った。

対処

config/database.yml
- encoding: utf8
+ encoding: utf8mb4
+ charset: utf8mb4
+ collation: utf8mb4_bin

テーブルを作り直す。

rails db:rollback
rails db:migrate

参考

1
0
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
1
0