如何创建迁移以仅在存在时删除索引,而不是如果不存在则抛出exception?

目前,如果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是否采取任何选项以静默方式继续,如果它无法删除索引而不是引发错误?

你可以使用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