Created
November 19, 2015 16:21
-
-
Save fabdbt/f4c7e632278f4cbc9f96 to your computer and use it in GitHub Desktop.
Convert the table associated to a model into 'utf8_general_ci' (string columns + table)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ConvertToUtf8 | |
DEFAULT_CONVERT_CHARACTER = 'utf8' | |
DEFAULT_CONVERT_COLLATE = 'utf8_general_ci' | |
DEFAULT_CONVERT_COLUMNS = { | |
# ActiveRecord: SQL | |
string: 'varchar(255)', | |
text: 'text' | |
} | |
# Call example : ConvertToUtf8.new User | |
def initialize model_class, **options | |
options[:convert_columns] ||= ConvertToUtf8::DEFAULT_CONVERT_COLUMNS | |
options[:convert_character] ||= ConvertToUtf8::DEFAULT_CONVERT_CHARACTER | |
options[:convert_collate] ||= ConvertToUtf8::DEFAULT_CONVERT_COLLATE | |
model_class = model_class.constantize unless model_class.is_a? Class | |
model_columns = model_class.columns | |
options[:convert_columns].each do |rails_column, sql_column| | |
fields_to_convert = model_columns.select{ |c| c.type == rails_column }.map(&:name) | |
fields_to_convert.each do |field| | |
ActiveRecord::Base.connection.execute("ALTER TABLE `#{model_class.table_name}` MODIFY `#{field}` #{sql_column} CHARACTER SET #{options[:convert_character]} COLLATE #{options[:convert_collate]};") | |
end | |
end | |
ActiveRecord::Base.connection.execute("ALTER TABLE `#{model_class.table_name}` CONVERT TO CHARACTER SET #{options[:convert_character]} COLLATE #{options[:convert_collate]};") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment