我正在开发一个Rails应用程序,用户可以将照片上传到他们的个人资料中.每张照片都有一个标题,应该支持表情符号.尽管将表的编码更改为utf8mb4并修改
database.yml,但当我尝试在其标题中保存带有表情符号的照片时,MySQL会返回错误“错误的字符串值”.
该应用程序正在使用Ruby 2.3.0的Rails 5.0.0.1,MysqL正在使用5.7.16版本.
迁移文件:
class CreateUserPhotos < ActiveRecord::Migration[5.0] def change create_table :user_photos do |t| t.string :title t.string :filename,null: false t.integer :visibility,null: false,default: 0 t.belongs_to :user,foreign_key: true,index: true t.timestamps end reversible do |dir| dir.up do execute "ALTER TABLE `user_photos` CHANGE `title` `title` VARCHAR(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" end dir.down do execute "ALTER TABLE `user_photos` CHANGE `title` `title` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci;" end end end end
database.yml文件:
production: adapter: MysqL2 encoding: utf8mb4 reconnect: false database: app_db pool: 5 username: app_user password: app_password host: localhost socket: /var/run/MysqLd/MysqLd.sock collation: utf8mb4_unicode_ci
解决方法
尝试将表的排序规则设置为utf8mb4_bin而不是utf8mb4_unicode_ci:
ALTER TABLE user_photos CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin
并且还更改database.yml中的collation属性值