Skip to content

Instantly share code, notes, and snippets.

@vagnerzampieri
Created October 31, 2014 18:06
Show Gist options
  • Save vagnerzampieri/03bf971891ee63487a59 to your computer and use it in GitHub Desktop.
Save vagnerzampieri/03bf971891ee63487a59 to your computer and use it in GitHub Desktop.
Migration with constraint to foreign_key.
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.references :post, null: false
t.references :user, null: false
t.text :description
t.timestamps
end
reversible do |dir|
dir.up do
execute <<-SQL
ALTER TABLE comments
ADD CONSTRAINT comments_post_id_fk
FOREIGN KEY (post_id)
REFERENCES posts(id);
ALTER TABLE comments
ADD CONSTRAINT comments_user_id_fk
FOREIGN KEY (user_id)
REFERENCES users(id);
SQL
end
dir.down do
execute <<-SQL
ALTER TABLE comments
DROP CONSTRAINT comments_post_id_fk;
ALTER TABLE comments
DROP CONSTRAINT comments_user_id_fk;
SQL
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment