web-dev-qa-db-ja.com

インデックスが存在しない場合に例外をスローするのではなく、存在する場合にのみインデックスを削除する移行を作成する方法は?

現在、booksテーブルにcreated_atまたはupdated_atフィールドがない場合、現在の移行は失敗する可能性があります。

class AddTimestampIndexes < ActiveRecord::Migration
  def up
    remove_index :books, :created_at
    remove_index :books, :updated_at

    add_index  :books, :created_at
    add_index  :books, :updated_at
  end

  def down
    remove_index :books, :created_at
    remove_index :books, :updated_at
  end
end

remove_indexは、エラーを発生させるのではなく、インデックスの削除に失敗した場合、静かに続行するオプションを取りますか?

30
h2o

移行内でindex_exists?メソッドを使用して、削除する必要のあるインデックスが実際に存在するかどうかをテストできます。

こちらのドキュメントをご覧ください: http://apidock.com/Rails/ActiveRecord/ConnectionAdapters/SchemaStatements/index_exists%3F

私はそれをテストしていませんが、次のようなものを使用できるはずです。

class AddTimestampIndexes < ActiveRecord::Migration
  def up
    remove_index :books, :created_at if index_exists?(:books, :created_at)
    remove_index :books, :updated_at if index_exists?(:books, :updated_at)

    add_index  :books, :created_at
    add_index  :books, :updated_at
  end

  def down
    remove_index :books, :created_at
    remove_index :books, :updated_at
  end
end

ものの見た目では、実際に存在しない場合にのみ作成したいですか?これは、移行に適している場合があります。

class AddTimestampIndexes < ActiveRecord::Migration
  def up
    add_index  :books, :created_at unless index_exists?(:books, :created_at)
    add_index  :books, :updated_at unless index_exists?(:books, :updated_at)
  end

  def down
    remove_index :books, :created_at
    remove_index :books, :updated_at
  end
end
57
Jon