Ruby-on-rails Rails 迁移:检查存在并继续?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1645230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:53:47  来源:igfitidea点击:

Rails Migrations: Check Existence and Keep Going?

ruby-on-railsmigration

提问by Dan Rosenstark

I was doing this kind of thing in my migrations:

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

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

but it turns out that, while this works for SQLite, it does not work for PostgreSQL. It seems like if the add_column blows up, even if the Exception is caught,the transaction is dead and so the Migration can't do any additional work.

但事实证明,虽然这适用于 SQLite,但它不适用于 PostgreSQL。看起来如果 add_column 爆炸了,即使捕获到异常,事务也死了,因此迁移无法做任何额外的工作。

Is there any non-DB sepecificways to check if a column or table already exist? Failing that, is there any way to get my rescue block to really work?

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

回答by Tobias Cohen

As of Rails 3.0 and later, you can use column_exists?to check for the existance of a column.

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

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

There's also a table_exists?function, which goes as far back as Rails 2.1.

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

回答by SG 86

Or even shorter

甚至更短

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

回答by JellicleCat

For Rails 2.X, you can check the existence of columns with the following:

对于Rails 2.X,您可以使用以下内容检查列是否存在:

columns("[table-name]").index {|col| col.name == "[column-name]"}

If it returns nil, no such column exists. If it returns a Fixnum, then the column does exist. Naturally, you can put more selective parameters between the {...}if you want to identify a column by more than just its name, for example:

如果它返回 nil,则不存在这样的列。如果它返回一个 Fixnum,那么该列确实存在。当然,{...}如果您想通过不仅仅是名称来标识列,则可以在 之间放置更多选择性参数,例如:

{ |col| col.name == "foo" and col.sql_type == "tinyint(1)" and col.primary == nil }

(this answer first posted on How to write conditional migrations in rails?)

(这个答案首先发布在如何在 Rails 中编写条件迁移?

回答by Denis Neverov

add_column :statuses, :hold_reason, :string unless Status.column_names.include?("hold_reason")

add_column :statuses, :hold_reason, :string unless Status.column_names.include?("hold_reason")