lar*_*hao 5 mysql encoding ruby-on-rails ruby-on-rails-3
我有一个使用Mysql 5.5.34utf8编码的Rails 3.2项目.现在我发现使用utf8编码Mysql无法保存代表表情符号的unicode字符.
那么我可以将整个数据库转换为使用utf8mb4我在网络上找到的可以容纳4字节unicode包括表情符号的编码吗?
我在数据库中的所有信息是否都包含在utf8mb4编码中?如果我这样做,我会面临数据损失吗?
有没有Rails提供的方法呢?
非常感谢您的帮助.
实际上你只需要迁移你想要用utf8mb4编码的列。
execute("ALTER TABLE yourtablename MODIFY yourcolumnname TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;")
Run Code Online (Sandbox Code Playgroud)
如果您打算迁移数据本身,则可能无法实现,因为常见的 utf8 由 3 字节字符组成,而 utf8mb4 由 4 字节字符组成。因此,您的数据库中可能已经有损坏的数据。
此外,Rails 3.2 在 ActiveSupports JSON 编码中存在编码问题。如果您计划使用 json 和表情符号,则需要添加如下补丁(基于 Rails 4 中的解决方案https://github.com/rails/rails/blob/4-0-stable/activesupport /lib/active_support/json/encoding.rb)或者只是升级到 Rails 4。
module ActiveSupport
module JSON
module Encoding
class << self
def escape(string)
if string.respond_to?(:force_encoding)
string = string.encode(::Encoding::UTF_8, :undef => :replace).force_encoding(::Encoding::BINARY)
end
json = string.gsub(escape_regex) { |s| ESCAPED_CHARS[s] }
json = %("#{json}")
json.force_encoding(::Encoding::UTF_8) if json.respond_to?(:force_encoding)
json
end
end
end
end
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2465 次 |
| 最近记录: |