module MigrationHelper
def add_foreign_key(from_table, from_column, to_table, options = {})
to_column = options.fetch(:to_column, 'id')
suffix = options[:suffix]
on_delete = options[:delete]
on_update = options[:update]
on_delete = 'SET NULL' if on_delete == :set_null
on_update = 'CASCADE' if on_update == :cascade
constraint_name = "fk_#{from_table}_#{to_table}"
constraint_name += "_#{suffix}" unless suffix.nil?
sql = "ALTER TABLE #{from_table} "
sql += "ADD CONSTRAINT #{constraint_name} "
sql += "FOREIGN KEY (#{from_column}) REFERENCES #{to_table}(#{to_column}) "
sql += "ON DELETE #{on_delete} " if on_delete
sql += "ON UPDATE #{on_update}" if on_update
execute sql
end
def remove_foreign_key(from_table, to_table, suffix = nil)
constraint_name = "fk_#{from_table}_#{to_table}"
constraint_name += "_#{suffix}" unless suffix.nil?
# note, you may have to use DROP KEY here - see MySQL docs for details
execute "ALTER TABLE #{from_table} DROP FOREIGN KEY #{constraint_name}"
end
end
ActiveRecord::Migration.extend(MigrationHelper)