如何创建迁移以仅在索引存在时删除索引,而不是在不存在时抛出异常? [英] How to create a migration to remove an index only if it exists, rather than throwing an exception if it doesn't?
问题描述
现在,如果 books
表没有 created_at
或 updated_at
字段,当前迁移可能会失败:
Right now, the current migration might fail, if the books
table doesn't have created_at
or updated_at
fields:
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
无法删除索引而不是引发错误,它是否会采取任何静默方式继续进行?
Does remove_index
take any options to silently proceed if it fails to remove the index rather than raising an error?
推荐答案
您可以在迁移中使用 index_exists?
方法来测试您需要删除的索引是否确实存在.
You can use the index_exists?
method within your migration to test whether the index you need to remove is actually there.
看看这里的文档:http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/index_exists%3F
我没有测试过,但你应该可以使用这样的东西:
I've not tested it, but you should be able to use something like this:
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
虽然,从表面上看,如果它们不存在,您真的只想创建它们吗?这可能更适合您的迁移:
Although, by the looks of things, you really only want to create them if they don't exist? This might be more appropriate for your migration:
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
这篇关于如何创建迁移以仅在索引存在时删除索引,而不是在不存在时抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!