Rails中文問題解決方法(FreeBSD+MySQL)
有關(guān)Rails中文問題,在網(wǎng)上看了很多的解決方法,都沒有成功,經(jīng)過多次試驗,終于成功,并且覺得網(wǎng)上有些內(nèi)容寫得不對,在這里,我總結(jié)一下我的中文處理方法。
Rails中文問題解決方案步驟
1.操作系統(tǒng):FreeBSD
2.數(shù)據(jù)庫是mysql 5.1.33 在安裝在FreeBSD之后,在默認路徑是/usr/local/mysql。 在support-files文件夾中,將一個配置文件復(fù)制到/etc中,并改名為my.cnf,這就是mysql的默認配置文件,修改此文件,在文件中的[client],[mysqld],[mysql]部分增加“default-character-set=gbk”。重啟數(shù)據(jù)庫,就可以將數(shù)據(jù)庫一些配置改成gbk。進行數(shù)據(jù)庫后,運行“ show variables like 'character_set_%';”后結(jié)果:
- +--------------------------+----------------------------------+
- | Variable_name | Value |
- +--------------------------+----------------------------------+
- | character_set_client | gbk |
- | character_set_connection | gbk |
- | character_set_database | utf8 |
- | character_set_filesystem | binary |
- | character_set_results | gbk |
- | character_set_server | gbk |
- | character_set_system | utf8 |
- | character_sets_dir | /usr/local/mysql/share/charsets/ |
- +--------------------------+----------------------------------+
3.rails使用2.3.3,建立rails項目后,將config/database.yml中的encoding改為gbk.
4.在編寫程序時,使用utf-8編碼編寫.rb文件,如果頁面中提交的參數(shù)中有中文,那么提交后中文后變成亂碼,這樣就要用gbk將參數(shù)先進行轉(zhuǎn)碼(這個要根據(jù)你的程序進行編寫,我的程序 的公用部分這樣寫的)
在application_controller.rb中增加
- before_filter :set_charset
- def set_charset
- headers["Content-Type"] = "text/html; charset=utf-8"
- end
- #解析參數(shù)
- parameters = @request.parameters
- parameters.each do |key, value|
- #value is being encoded if chinese
- parameters[key] = gbk(value)
- end
- #from utf-8 to gb2312
- def self.gbk(text = '')
- return '' if text.blank?
- text = Iconv.conv('gb2312//IGNORE', 'utf-8//IGNORE', text)
- return text
- end
這樣在寫入數(shù)據(jù)庫中就是中文了。
5.在取出數(shù)據(jù)庫信息后要進行utf8編碼
6.在輸出頁面中要加入“< meta http-equiv="content-type" content="text/html; charset=utf-8"/>”
這樣就可能正確顯示中文了,總之,轉(zhuǎn)碼的過程是:utf8->gbk這是從頁面到數(shù)據(jù)庫的過程,從數(shù)據(jù)庫到頁面是gbk->utf8。
這樣就介紹了Rails中文問題的解決方法。本文來自Ming's Blog:《Rails, Mysql, FreeBSD中文問題解決》。
【編輯推薦】