Fork me on GitHub

Finding Stale Tables

2007-08-01

Here’s a simple rake task to help you find unused db tables lying around in your application. Keep in mind it’s just a guess, showing any table that doesn’t constantize; if you’re using habtm tables, unconventional table names, or other such things, expect to see them show up as well.

namespace :app do
  namespace :stale do
    task :tables => :environment do
      tables = ActiveRecord::Base.connection.tables.reject do |table|
        table.classify.camelize.constantize rescue nil
      end - %w(schema_info)
      if tables.any?
        $stderr.puts "The following may be stale:"
        puts tables
      else
        $stderr.puts "No stale tables found"
      end
    end
  end
end

Discussion