Rails Migration to Convert all Table Names and Column Names to underscore

Ruby on Rails Add comments

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.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

One Response to “Rails Migration to Convert all Table Names and Column Names to underscore”

  1. Andreas Says:

    “Hope it helps.”

    Yes it does, thank you!

    Andreas

Leave a Reply

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in