Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
module MigrationHelper
#options are:
# :pk_table_name
# :pk_column_name
# :cascade_delete
# :cascade_update
def add_fk(fk_table_name, fk_column_name, options)
fk_table_name = fk_table_name.to_s
fk_column_name = fk_column_name.to_s
pk_table_name = options[:pk_table_name] || fk_column_name[0, fk_column_name.index("_id") || fk_column_name.length]
pk_column_name = options[:pk_column_name] || "id"
cascade_delete = options[:cascade_delete] ? "on delete cascade" : ""
cascade_update = options[:cascade_update] ? "on update cascade" : ""
execute "alter table #{fk_table_name} add constraint fk_#{fk_table_name}_#{fk_column_name} foreign key (#{fk_column_name}) references #{pk_table_name.to_s} (#{pk_column_name.to_s}) #{cascade_delete} #{cascade_update}"
execute "create index idx_#{fk_table_name}_#{fk_column_name} on #{fk_table_name} (#{fk_column_name})"
end
def drop_fk(fk_table_name, fk_column_name)
execute "drop index #{fk_table_name}.idx_#{fk_table_name}_#{fk_column_name}"
execute "alter table #{fk_table_name.to_s} drop constraint fk_#{fk_table_name.to_s}_#{fk_column_name.to_s}"
end
end
class ActiveRecord::Migration
extend MigrationHelper
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment