Skip to content

Instantly share code, notes, and snippets.

@jamesmk
Last active April 18, 2019 21:34
Show Gist options
  • Save jamesmk/55850dd1a6298137040b to your computer and use it in GitHub Desktop.
Save jamesmk/55850dd1a6298137040b to your computer and use it in GitHub Desktop.
Rake task to convert MySQL DB's tables and columns to a specific encoding and collation.
namespace :db do
desc "Convers the encoding and collation of database, tables and columns."
task :convert_encoding, [:character_set, :collation] => :environment do |t, args|
args.with_defaults(character_set: 'utf8', collation: 'utf8_general_ci')
ActiveRecord::Base.connection.tables.each do |table|
ActiveRecord::Base.connection.execute("ALTER TABLE `#{table}` CONVERT TO CHARACTER SET #{args.character_set} COLLATE #{args.collation};")
end
end
end
# or paste this into a rails console
character_set = 'utf8'
collation = 'utf8_general_ci'
ActiveRecord::Base.connection.tables.each do |table|
ActiveRecord::Base.connection.execute("ALTER TABLE `#{table}` CONVERT TO CHARACTER SET #{character_set} COLLATE #{collation};")
end
@nilesmc
Copy link

nilesmc commented Apr 7, 2016

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment