Skip to content

Instantly share code, notes, and snippets.

@amuntasim
Last active June 2, 2022 21:06
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save amuntasim/f3b12f20a30e9a9f3fb0 to your computer and use it in GitHub Desktop.
Save amuntasim/f3b12f20a30e9a9f3fb0 to your computer and use it in GitHub Desktop.
##Create a migration
### rails g migration make_unicode_friendly
class MakeUnicodeFriendly < ActiveRecord::Migration
def change
alter_database_and_tables_charsets "utf8", "utf8_general_ci"
end
private
def alter_database_and_tables_charsets charset = default_charset, collation = default_collation
case connection.adapter_name
when 'Mysql2'
execute "ALTER DATABASE #{connection.current_database} CHARACTER SET #{charset} COLLATE #{collation}"
connection.tables.each do |table|
execute "ALTER TABLE #{table} CONVERT TO CHARACTER SET #{charset} COLLATE #{collation}"
end
else
# OK, not quite irreversible but can't be done if there's not
# the code here to support it...
raise ActiveRecord::IrreversibleMigration.new("Migration error: Unsupported database for migration to UTF-8 support")
end
end
def default_charset
case connection.adapter_name
when 'Mysql2'
execute("show variables like 'character_set_server'").fetch_hash['Value']
else
nil
end
end
def default_collation
case connection.adapter_name
when 'Mysql2'
execute("show variables like 'collation_server'").fetch_hash['Value']
else
nil
end
end
def connection
ActiveRecord::Base.connection
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment