在使用rails做web开发的时候,数据库选用mysql会出现这种问题:
从web页面传入数据库的中文,会在mysql中显示为乱码,而在mysql中录入的数据会在web页面显示问号,原因就是字符集不统一,解决方案如下:
首先在rails新建项目的时候,在控制器的application.rb中加入如下代码:
class ApplicationController < ActionController::Base
# Pick a unique cookie name to distinguish our session data from others'
session :session_key => '_projectName_session_id'
after_filter :set_charset
def set_charset
content_type = headers["Content-Type"] || 'text/html'
if /^text\//.match(content_type)
headers["Content-Type"] = "#{content_type}; charset=utf-8"
suppress(ActiveRecord::StatementInvalid) do
ActiveRecord::Base.connection.execute 'SET NAMES utf8'
end
end
end
end
# Pick a unique cookie name to distinguish our session data from others'
session :session_key => '_projectName_session_id'
after_filter :set_charset
def set_charset
content_type = headers["Content-Type"] || 'text/html'
if /^text\//.match(content_type)
headers["Content-Type"] = "#{content_type}; charset=utf-8"
suppress(ActiveRecord::StatementInvalid) do
ActiveRecord::Base.connection.execute 'SET NAMES utf8'
end
end
end
end
在mysql中建立数据库时,选择编码类型为utf-8,或者将mysql的配置文件my.ini(xp下)中的default-character-set=设置成utf8, 文件中有两处需要修改,修改完成后,按照默认方式创建,即可解决开始的那个问题了!
本文转自 fsjoy1983 51CTO博客,原文链接:http://blog.51cto.com/fsjoy/83951,如需转载请自行联系原作者