现在,如果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
无法删除索引而不引起错误,是否采取任何选择以静默方式进行?
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
index_name_exists?(table_name, index_name)
方法,您可以通过它的名称检查索引。这对于检查是否存在多列索引很有帮助。