Created
January 23, 2011 04:04
-
-
Save wyanez/791801 to your computer and use it in GitHub Desktop.
[Rails] Helper para crear Foreign key en las migraciones de Rails
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
=begin | |
MigrationHelper | |
Funciones para la creacion de claves foraneas desde las migraciones | |
@author: William Yanez | |
Uso: class MyMigration < ActiveRecord::Migration | |
extend MigrationHelper | |
=end | |
module MigrationHelper | |
def add_foreign_key(tabla_org,campo,tabla_dest,options=nil) | |
constraint_name="fk_#{tabla_org}_#{campo}" | |
on_update=on_delete="RESTRICT" | |
options={} if options.nil? | |
on_update=options[:update] if options.has_key?(:update) | |
on_delete=options[:delete] if options.has_key?(:delete) | |
sql = "ALTER TABLE #{tabla_org} ADD CONSTRAINT #{constraint_name}" | |
sql << "FOREIGN KEY (#{campo}) REFERENCES #{tabla_dest}(id)" | |
sql << "ON UPDATE #{on_update} ON DELETE #{on_delete}" | |
execute sql | |
end | |
def drop_foreign_key(tabla_org,campo) | |
constraint_name="fk_#{tabla_org}_#{campo}" | |
#Para PostgreSQL: | |
sql="ALTER TABLE #{tabla_org} DROP CONSTRAINT #{constraint_name}" | |
#Para MySQL: | |
#sql="ALTER TABLE #{tabla_org} DROP FOREIGN KEY #{constraint_name}" | |
execute sql | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment