Created
October 31, 2014 18:06
-
-
Save vagnerzampieri/03bf971891ee63487a59 to your computer and use it in GitHub Desktop.
Migration with constraint to foreign_key.
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
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