---
title: "冪等なマイグレーションを作成する"
description: "破壊的なマイグレーションを書くときは、テーブルを削除する場合には if\\exists: true を使い、カラムを追加または削除する場合にはテーブルの存在を確認してください…"
canonical: https://oozou.com/til/create-idempotent-migrations-28
locale: ja
date: 2020-10-13
topic: ruby-on-rails
---

# 冪等なマイグレーションを作成する

> 破壊的なマイグレーションを書くときは、テーブルを削除する場合には if\exists: true を使い、カラムを追加または削除する場合にはテーブルの存在を確認してください…

Published: 2020-10-13 · Topic: [ruby on rails](https://oozou.com/ja/til-topics/ruby-on-rails) ([markdown](https://oozou.com/ja/til-topics/ruby-on-rails.md))

破壊的なマイグレーションを書くときは、テーブルを削除する場合には *if\_exists: true* を使い、カラムを追加または削除する場合には *ActiveRecord::Base.connection.table\_exists?* でテーブルの存在を確認してください

ケース 1：

```ruby
def up
  drop_table :kittens, if_exists: true
end
```

ケース 2：

```ruby
def up
  return unless ActiveRecord::Base.connection.table_exists?(:kittens)
  add_column :kittens, :kind, :integer
end
```

---

Contact OOZOU: hello@oozou.com · +66 2544 0000 · https://oozou.com/ja/contact

More for AI agents: https://oozou.com/llms.txt · every page has a markdown twin at its URL plus ".md"
