Rails Migration to Convert all Table Names and Column Names to underscore
This 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]) }
end
def 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
end
def 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.
Andreas: "Hope it helps." Yes it does, thank you! Andreas
Posted: 30 August 2011