Created
June 26, 2009 22:44
-
-
Save fguillen/136799 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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