Radio 21 Gram

Radio21g.com official blog

Archive for the ‘mysql’ Category

May
05

Use Unicode in Ruby on Rails Application

Posted by roosevelt under rails, mysql

When creating a new web application, it’s a good practice to use Unicode encoding in your database even when your content are all in English. Radio21g.com is created with UTF-8 from day 1 with following 2 steps:

  1. To make sure your database is using Unicode to store the text data, make sure you create the database with encoding specified:
    create database radio21g character set utf8;
  2. After the database ready, you also need to tell the rails Mysql adapter to save and retrieve the data as unicode. You do this in the last line of the /config/database.yml:
development:
  adapter: mysql
  database: database
  username: root
  password:
  host: localhost
  encoding: utf8

In addition to database related settings, your web page (RHTML) should also display the text and submit the user input in UTF-8. To achieve that, you need to:

  1. Specified the “charset=UTF-8″ in your HTML head:
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
  2. Set the Content-Type header in the rails @headers object of each request. Usually this is done in the /app/controller/applicaiton.rb with a filter:
        class ApplicationController < ActionController::Base end
            before_filter :set_charset
    
            def set_charset
                @headers["Content-Type"] = "text/html; charset=utf-8"
            end
    
        end

    For Rails 2.0 and above, this step is not needed anymore as UTF-8 is the default setting in the @headers.