Skip to content

Instantly share code, notes, and snippets.

@fguillen
Created June 26, 2009 22:44
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 fguillen/136799 to your computer and use it in GitHub Desktop.
Save fguillen/136799 to your computer and use it in GitHub Desktop.
# fguillen 2009-06-25:
# inspired on: http://github.com/patientslikeme/migration_helpers/tree/
#
# add a foreign key constraint
# add_foreign_key 'books', 'author_id', 'authors'
#
class ActiveRecord::Migration
def self.add_foreign_key(
table,
target_table,
column = "#{target_table.singularize}_id",
target_column = "id",
constraint_name = "fk_#{table.to_s}_#{target_table.to_s}"
)
execute(
"ALTER TABLE #{table.to_s}" +
" ADD CONSTRAINT #{constraint_name.to_s}" +
" FOREIGN KEY (#{column.to_s})" +
" REFERENCES #{target_table.to_s} (#{target_column.to_s});"
)
end
def self.remove_foreign_key(
table,
target_table,
constraint_name = "fk_#{table.to_s}_#{target_table.to_s}"
)
execute "ALTER TABLE #{table.to_s} DROP FOREIGN KEY #{constraint_name};"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment