gpt4 book ai didi

ruby-on-rails - Rails 迁移 : Check Existence and Keep Going?

转载 作者:行者123 更新时间:2023-12-03 05:21:23 24 4
gpt4 key购买 nike

我在迁移中做了这样的事情:

add_column :statuses, :hold_reason, :string rescue puts "column already added"

但事实证明,虽然这适用于 SQLite,但不适用于 PostgreSQL。看起来,如果 add_column 崩溃,即使捕获了异常,事务也已终止,因此迁移无法执行任何额外工作。

是否有任何非数据库特定方法来检查列或表是否已存在?如果做不到这一点,有什么办法让我的救援 block 真正发挥作用吗?

最佳答案

从 Rails 3.0 及更高版本开始,您可以使用 column_exists?检查列是否存在。

unless column_exists? :statuses, :hold_reason
add_column :statuses, :hold_reason, :string
end

还有一个table_exists?函数,其历史可以追溯到 Rails 2.1。

关于ruby-on-rails - Rails 迁移 : Check Existence and Keep Going?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1645230/

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