Skip to content

Instantly share code, notes, and snippets.

@meatherly
Created April 2, 2015 22:42
Show Gist options
  • Save meatherly/81041518da4fc0ef9a83 to your computer and use it in GitHub Desktop.
Save meatherly/81041518da4fc0ef9a83 to your computer and use it in GitHub Desktop.
Add cascading foreign keys to app
class TableUpdater
attr_accessor :tables, :migration_statements
def initialize
@tables = ActiveRecord::Base.connection.tables.reject{|t| t == "schema_migrations"}
@migration_statements = []
end
def make_migration_file
@tables.each do |table|
foreign_keys = ActiveRecord::Base.connection.foreign_keys(table)
foreign_keys.each do |foreign_key|
from_table = foreign_key.from_table
to_table = foreign_key.to_table
remove = "remove_foreign_key :#{from_table}, :#{to_table}"
add = "add_foreign_key :#{from_table}, :#{to_table}, on_delete: :cascade"
@migration_statements << remove
@migration_statements << add
end
end
puts @migration_statements
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment