我正在运行以下给定的迁移操作,以向我的blood
枚举添加额外的价值。
class AddTypesToBlood < ActiveRecord::Migration[5.2]
def up
execute <<-SQL
ALTER TYPE blood ADD ATTRIBUTE 'NA';
SQL
end
def down
execute <<-SQL
ALTER TYPE blood DROP ATTRIBUTE 'NA';
SQL
end
end
但是上述迁移引发错误。请查看终端屏幕截图以了解错误。
答案 0 :(得分:1)
看看the documentation,您会发现语法是
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.AutoResizeColumns();
dataGridView1.AutoResizeRows();
}
在PostgreSQL中无法从枚举类型中删除值,因此您将无法撤消该更改。
如果属性的值范围发生变化,请不要使用枚举类型。
答案 1 :(得分:1)
由于要通过SQL添加新的枚举值,因此我想您也通过SQL将列定义为枚举。所以 using Postgres's Documentation:
ALTER TYPE名称添加值new_enum_value [{之后} existing_enum_value]
试一下:
def up
execute <<-SQL
ALTER TYPE blood ADD VALUE 'NA';
SQL
end
def down
execute <<-SQL
ALTER TYPE blood DROP VALUE 'NA';
SQL
end
在Rails中进行枚举的另一种方法是在模型中定义枚举。因此,您可以做的是让模型的属性(称为blood
)的类型为integer
。然后在模型中可以执行以下操作:
class Model < ApplicationRecord
enum blood: [
:A,
:B,
:AB,
:O,
:NA
]
end
这样,当您要修改枚举的值时,不必创建另一个迁移。这样做的另一个好处是您可以使用字符串(或符号)作为枚举的值。即:
# Both work
model.update_attributes(blood: 'O')
model.update_attributes(blood: :O)
当您访问blood
属性时,仍然会返回一个字符串:
puts model.blood # => "O"
答案 2 :(得分:0)
接受的答案不起作用,因为没有 DROP VALUE
这样的东西(并且在以前的 Postgres 版本中没有)
步骤基本上是:
以下是基本步骤的示例:
https://www.munderwood.ca/index.php/2015/05/28/altering-postgresql-columns-from-one-enum-to-another/