運行環境:netbeans IDE 6.1
今天下午本來打算對院務系統做個模擬聯繫。按照自己習慣,先在控制器controler中生成一個新的控制器,之後在view中建立控制器的方法xxx.rhtml。之後在rhtml中寫上了<h1>院務系統</h1>。運行了一下,在瀏覽器中顯示的是亂碼。太鬱悶了。
在網上找了很多方法,試了一下午,都沒有試出來。
包括以下的方法
把xxx.rhtml文件用記事本打開,然後另存爲編碼爲utf-8的xxx,rhtml。再運行一下,果然可以輸出中文,但是我再用netbeans打開,rhtml中的中文卻是亂碼的。更加鬱悶。這樣多不方便以後編譯。
還有一種方法,網上很多人在用的,不過對於我沒有用。
修改ApplicationController 如下:class ApplicationController < ActionController::Base
before_filter :configure_charsets
def configure_charsets
# @headers["Content-Type"] = "text/html; charset=utf-8"
@response.headers["Content-Type"] = "text/html; charset=utf-8"
# Set connection charset. MySQL 4.0 doesn??t support this so it
#will throw an error, MySQL 4.1 needs this
suppress(ActiveRecord::StatementInvalid) do
ActiveRecord::Base.connection.execute 'SET NAMES utf8'
end
end
end
請在rhtml中,或者適當的layout中,加上:
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
在config/database.yml修改如下:development:
adapter: mysql
database: depot_development
encoding: utf8 *注意空格*
username: root
password:
host: localhost
保存後,重啓ROR,啓動app,再次ruby script/generate scaffold Product Admin應該就行了。數據庫裏的表應該都是utf8_general_ci,rhtml也應該都是utf-8編碼。/app/views/layouts/admin.rhtml中加上<meta>標籤。
試了一個下午,絕望死了。最後是師兄發現問題所在。(他太牛了,看了幾下,就找出問題所在)
原來我在項目的屬性中的編碼,沒有設置是utf-8的。汗......