LoginSignup
0
1

More than 3 years have passed since last update.

色々なrailsのマイグレーション操作

Last updated at Posted at 2020-10-31

この記事で扱うこと

  • NOT NULL制約の付いたカラムに制約を追加/削除する方法
  • 複数カラムを紐付けたカラムからindexを削除する方法
  • reference型で作成した外部キーをつけたカラムを削除する方法

NOT NULL制約を追加/削除する

NOT NULL制約を追加したいとき

def up
  change_column_null :posts, :content, false
end

def down
  change_column_null :posts, :content, true
end

ポイントはchangeメソッドを使用せず、up/downメソッドを使用すること

NOT NULL制約を削除したいとき

def up
  change_column_null :posts, :content, true
end

def down
  change_column_null :posts, :content, false
end

複合キーindexを付けたカラムからindexを削除する

def change
  remove_index :likes, column: [:user_id, :post_id], unique: true
end

単一カラムからindexを削除する時は以下のように

def change
  remove_index :likes, column: :micropost_id, unique: true
end

reference型で作成した外部キーをつけたカラムを削除する方法

def change
  remove_reference :posts, :user, null: false, foreign_key: true
end

foreign_key: trueで外部キーを設定していたらそれもつけてあげると良いです

おまけ

あるカラムにindexが付いているか確認する(MySQLにて)

mysql > SHOW CREATE TABLE tbl_name

参考

https://dev.mysql.com/doc/refman/5.6/ja/show-create-table.html

https://railsguides.jp/active_record_migrations.html

https://qiita.com/akinov/items/852fe789fe98a44350a9

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1