Rails : convert all tables to utf8 2

Posted by Antonin AMAND Tue, 06 Nov 2007 15:42:00 GMT

I sometimes need to convert old rails mysql databases to use unicode (utf8)

here is a way to do this quickly :

require 'rubygems'
require 'active_record'

db = "my_database"

sqlconn = ActiveRecord::Base.establish_connection(
  :adapter  => "mysql", 
  :host     => "localhost", 
  :username => "root", 
  :password => "", 
  :database => db
)

conn = ActiveRecord::Base.send(sqlconn.adapter_method,sqlconn.config)

conn.tables.each do |table|
    q = "ALTER TABLE #{table} CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci"
    puts q
    conn.execute q
end 
conn.execute("ALTER DATABASE #{db} DEFAULT CHARACTER SET utf8 ;")

edit : see Agouti’s comment

Comments

Leave a comment

  1. Agouti 2 months later:

    Very useful script, thanks. But you make a little error in the last line, the arg is 'db' not 'database'.

  2. agouti 9 months later:

    comment.body.gsub!(/make/, 'made')

Comments