gpt4 book ai didi

ruby-on-rails - 如何创建迁移以仅在索引存在时删除索引,而不是在不存在时抛出异常?

转载 作者:行者123 更新时间:2023-12-03 08:36:51 25 4
gpt4 key购买 nike

现在,当前迁移可能会失败,如果 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

关于ruby-on-rails - 如何创建迁移以仅在索引存在时删除索引,而不是在不存在时抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21795023/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com