如何创建仅在存在索引时才删除索引的迁移,而不是在不存在时引发异常?

问题描述 投票:33回答:2

现在,如果books表中没有created_atupdated_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无法删除索引而不引起错误,是否采取任何选择以静默方式进行?

ruby-on-rails ruby-on-rails-4 rails-migrations
2个回答
61
投票
您可以在迁移过程中使用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


0
投票
还有index_name_exists?(table_name, index_name)方法,您可以通过它的名称检查索引。这对于检查是否存在多列索引很有帮助。

文档-index_name_exists

© www.soinside.com 2019 - 2024. All rights reserved.