LoginSignup
25
15

More than 5 years have passed since last update.

migrationでrollback可否でchangeかup/downを使い分ける

Last updated at Posted at 2019-03-03

migrationにおいてchangeで書いてもrollbackできるもの、up/downで書かなくてはrollbackできないものをまとめました。
初投稿です。よろしくお願いします。

rollbackできる(changeでOK)

カラムを追加する

rails g migration AddColumnUsers

class AddColumnUser < ActiveRecord::Migration[6.0]
  def change
    add_column :users, :age, :integer
  end
end

カラムの名前を変更する

class RenameColumnFilmsReviewsFromNameToTitle < ActiveRecord::Migration[6.0]
  def change
    rename_column :films_reviews, :name, :title
  end
end

カラムにindexを追加する


class AddIndexToUserOfName < ActiveRecord::Migration[6.0]
  def change
    add_index :users, :name_badge: 
  end
end

カラムにデフォルト値を設定する(change_column_defaultを使う)


class ChangeColumnDefaultUserOfSocial < ActiveRecord::Migration[6.0]
  def change
    change_column_default :users, :social, from: nil, to: false
  end
end 

rollbackできない(up/downで書く)

changeで書くと以下のエラーが発生するもの

Caused by:
ActiveRecord::IrreversibleMigration: 

This migration uses change_column, which is not automatically reversible.
To make the migration reversible you can either:
1. Define #up and #down methods in place of the #change method.
2. Use the #reversible method to define reversible behavior.

カラムのデータ型を変更する

rails g migration ChangeColumnUsersToGender


class ChangeDataUserToGender < ActiveRecord::Migration[6.0]
  def up
    change_column :users, :gender, :boolean
  end

  def down
    change_column :users, :gender, :integer
  end
end

カラムにnullを許可しないよう変更する


class ChangeColumnUserForName < ActiveRecord::Migration[6.0]
  def up
    change_column :users, :name, :string, null: false
  end

  def down
    change_column :users, :name, :string, null: true
  end
end 

カラムにデフォルト値を設定する(change_column_defaultを使わない場合)


# change_column_defaultを使うとchangeでもrollbackできる
class AddDefaultValueUserOfOccupation < ActiveRecord::Migration[6.0]
  def up
    change_column :users, :occupation, :integer, default: 1
  end

  def down
    # default値を指定していなかった場合 default:nilと書かないとrollback時にnilに戻らない
    change_column :users, :occupation, :integer, default: nil
  end
end

RailsGuideによると複雑なことやるときはreversibleを使いましょうというのもあるけど、それはまた別の機会に。(また今度というときはまず書かないかもですが:expressionless:

マイグレーションを逆方向に実行 (ロールバック) する方法が推測できない場合、reversible を使います。

25
15
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
25
15