Ruby on Rails - 表情符号未保存在MySQL中

时间:2022-06-18 23:26:51

I'm working on a Rails app where users can upload photos to their profiles. Every photo has a title, which is supposed to support emoji. Despite changing encoding of the table to utf8mb4 and modifying database.yml when i try to save a photo with emoji in its title MySQL returns an error 'incorrect string value'.

我正在开发一个Rails应用程序,用户可以将照片上传到他们的个人资料中。每张照片都有一个标题,应该支持表情符号。尽管将表的编码更改为utf8mb4并修改database.yml,但当我尝试在其标题中保存带有表情符号的照片时,MySQL会返回错误“错误的字符串值”。

The app is working on Rails 5.0.0.1 with Ruby 2.3.0, MySQL is working on version 5.7.16.

该应用程序正在使用Ruby 2.3.0的Rails 5.0.0.1,MySQL正在使用5.7.16版本。

Migration file:

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 file:

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

1 个解决方案

#1


4  

Try to set table's collation to utf8mb4_bin instead of utf8mb4_unicode_ci:

尝试将表的排序规则设置为utf8mb4_bin而不是utf8mb4_unicode_ci:

ALTER TABLE user_photos CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin

And also change collation property value in database.yml

并且还更改database.yml中的collat​​ion属性值

#1


4  

Try to set table's collation to utf8mb4_bin instead of utf8mb4_unicode_ci:

尝试将表的排序规则设置为utf8mb4_bin而不是utf8mb4_unicode_ci:

ALTER TABLE user_photos CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin

And also change collation property value in database.yml

并且还更改database.yml中的collat​​ion属性值