Skip to content

Instantly share code, notes, and snippets.

@leikind
Created February 8, 2011 15:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leikind/816579 to your computer and use it in GitHub Desktop.
Save leikind/816579 to your computer and use it in GitHub Desktop.
desc 'generate add_index declarations for all foreign key fields'
task :indexes => :environment do
files = nil
Dir.chdir(File.join(RAILS_ROOT, "app/models" )) do
files = Dir["*.rb"]
end
models = []
files.each do |m|
class_name = m.sub(/\.rb$/, '').camelize
begin
klass = class_name.split('::').inject(Object){ |klass,part| klass.const_get(part) }
if klass < ActiveRecord::Base && !klass.abstract_class?
models << klass
end
rescue Exception
end
end
res = models.map do |klass|
table_name = klass.table_name
indexed_columns = []
res = klass.connection.execute("SHOW INDEX FROM #{table_name}")
while row = res.fetch_row
indexed_columns << row[4]
end
res = klass.columns.select{|col| col.name =~ /_id$/ }.reject{|col| indexed_columns.index col.name }.map do |column|
" add_index :#{table_name}, :#{column.name}"
end
res.blank? ? nil : res.join("\n")
end.compact.join("\n")
down = res.gsub(/add_index/, 'remove_index')
puts %"def self.up\n#{res}\nend\n\ndef self.down\n#{down}\nend\n"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment