Created
January 25, 2012 18:26
-
-
Save pragdave/1677738 to your computer and use it in GitHub Desktop.
Simple helper to add fk constraints in Rails migrations
This file contains 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
module MigrationHelpers | |
def fk(from_table, from_column, to_table=from_column.to_s.sub(/_id$/, 's')) | |
constraint_name = "fk_#{from_table}_#{from_column}" | |
execute %{alter table #{from_table} | |
add constraint #{constraint_name} | |
foreign key (#{from_column}) | |
references #{to_table}(id)} | |
end | |
def drop_fk(from_table, from_column) | |
constraint_name = "fk_#{from_table}_#{from_column}" | |
execute %{alter table #{from_table} 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