Rails Migration to Convert all Table Names and Column Names to underscore
Ruby on Rails Add commentsThis may be useful for legacy database, whose table and column names are in CamelCase. Use with extreme caution:
class ChangeAllColumnsToUnderscore < ActiveRecord::Migration
include ActiveRecord::ConnectionAdapters::SchemaStatements
require ‘active_record/connection_adapters/abstract_adapter’#not needed in Rails 3
#pilfered from here:
#http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-column_exists-3F
def self.column_exists?(table_name, column_name, type = nil, options = {})
columns(table_name).any?{ |c| c.name == column_name.to_s &&
(!type || c.type == type) &&
(!options[:limit] || c.limit == options[:limit]) &&
(!options[:precision] || c.precision == options[:precision]) &&
(!options[:scale] || c.scale == options[:scale]) }
enddef self.up
tables.reject {|t| t == “schema_migrations”}.each do |table|
columns(table.to_sym).each do |column|
unless self.column_exists?(table.to_sym, column.name.underscore.to_sym)
rename_column table.to_sym, column.name.to_sym, column.name.underscore.to_sym
end
end
unless table_exists?(table.underscore.to_sym)
rename_table table, table.underscore
end
end
enddef self.down
tables.reject {|t| t == “schema_migrations”}.each do |table|
columns(table.to_sym).each do |column|
unless column_exists?(table.to_sym, column.name.camelize.to_sym)
rename_column table.to_sym, column.name.to_sym, column.name.camelize.to_sym
end
end
unless table_exists?(table.camelize.to_sym)
rename_table table, table.camelize
end
end
end
end
Hope it helps.
November 4th, 2011 at 6:34 pm
“Hope it helps.”
Yes it does, thank you!
Andreas