DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Ruby On Rails - PostgreSQL Foreign Keys
To utilise foreign keys in my database while still using the super tidy Rails migrations, I created these migration helpers to CREATE and DROP foreign keys. NOTE: this was written for a PostgreSQL database so it will likely not work on other DBs.
def foreign_key(from_table, from_column, to_table)
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_foreign_key(from_table, from_column, to_table)
constraint_name = "fk_#{from_table}_#{from_column}"
execute %{ALTER TABLE #{from_table}
DROP CONSTRAINT #{constraint_name}}
end





