ROR 中文問題的通用解決方案

來源:互聯網
上載者:User

最近瘋狂的愛上了ROR,開始用它做些小東西,可是總是出現亂碼問題,最後Google以下,找到了很多的解決中文亂碼問題的思路,總結與大家分享之。

開發環境:RedRails       使用編碼:UTF-8             資料庫:MySql

  1. 在radrails中,請在project的property對話方塊中,左邊選中info節點,右邊設定編碼方式為UTF-8
  2. 修改MySQL的設定檔C:\Program Files\MySQL\MySQL Server 5.0\my.ini,改其中的兩處default-character-set=utf8,改完後重啟MySQL(windows服務)。這一步也可採用instance wizard來做。
  3. 修改ApplicationController 如下:
  4. 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

  5. 請在rhtml中,或者適當的layout中,加上:
  6. <meta http-equiv="content-type" content="text/html; charset=UTF-8">

  7. 在config/database.yml修改如下:
  8. 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>標籤。

    我用瞭解決了自己的中文亂碼問題,大家看看,希望可以和我一樣好運!!!

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.