LoginSignup
7
6

More than 3 years have passed since last update.

[Rails]マイグレーションファイルの削除方法

Posted at

はじめに

今回、マイグレーションファイルの削除手順を間違ったせいで過去に大変な思いをしたので、復習を兼ねて正しい手順の削除方法などを書いていきたいと思います

マイグレーションファイルについて

まずはマイグレーションファイルの確認方法

$ bundle exec rake db:migrate:status

database: pictweet_exam2_development

 Status   Migration ID    Migration Name
--------------------------------------------------
   up     20141014132556  Create tweets
   up     20141018070558  Devise create users
   up     20141018072348  Add nickname to users
   up     20141018084902  Add user id to tweets
   up     20141112144522  Remove name from tweets
   up     20160606020309  Create comments

マイグレーションファイルの一個前の削除

$ bundle exec rake db:rollback
== 20160606020309 CreateComments: reverting ===================================
-- drop_table(:comments)
   -> 0.0078s
== 20160606020309 CreateComments: reverted (0.0117s) ==========================

down状態になったか確認し、マイグレーションファイルを削除する。念の為schema.rbにデータがないか確認をするのもいいと思います。

$ bundle exec rake db:migrate:status

database: pictweet_exam2_development

 Status   Migration ID    Migration Name
--------------------------------------------------
   up     20141014132556  Create tweets
   up     20141018070558  Devise create users
   up     20141018072348  Add nickname to users
   up     20141018084902  Add user id to tweets
   up     20141112144522  Remove name from tweets
  down    20160606020309  Create comments

複数前のマイグレーションファイルの削除の場合はVERSIONに「Migration ID」を指定しrake db:migrate:downを使用します。
今回は20141018084902のtweetsモデルのuser idカラムのマイグレーションファイルを消して見たいと思います。

$ bundle exec rake db:migrate:down  VERSION=20141018084902
== 20141018084902 AddUserIdToTweets: reverting ================================
-- remove_column(:tweets, :user_id, :integer)
   -> 0.0251s
== 20141018084902 AddUserIdToTweets: reverted (0.0270s) =======================

マイグレーションのファイルがdownになっているのを確認後、マイグレーションファイルを削除する。

$ bundle exec rake db:migrate:status
database: pictweet_exam2_development

 Status   Migration ID    Migration Name
--------------------------------------------------
   up     20141014132556  Create tweets
   up     20141018070558  Devise create users
   up     20141018072348  Add nickname to users
  down    20141018084902  Add user id to tweets
   up     20141112144522  Remove name from tweets

まとめ

マイグレーションファイルの操作は本当慎重に行わないと色々不具合が出て大変ですよね。
削除に関しては必ずマイグレーションファイルがdownになっているのを確認するようにすれば大きなトラブルは起こらないかと思います。
間違えてマイグレーションファイルを作成しても焦らず、正しい手順で削除するようにしていこうと思います。

7
6
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
7
6