Rails 迁移 - 将整数列更改为数组整数 - Postgres

Sug*_*jan 5 postgresql casting ruby-on-rails

我在提供者模型中有一个 Benefit_type 整数列,它是一个枚举列。

提供者.rb

enum: ['abc', 'bcd']
Run Code Online (Sandbox Code Playgroud)

现在我想迁移到 array_enum

提供者.rb

array_enum: {'abc': 0, 'bcd': 1}
Run Code Online (Sandbox Code Playgroud)

因此,为了适应这一更改,我想将列更改为整数数组。在我的迁移中,

change_column :providers, :benefit_type, :integer, array: true, default: {}, using: "(string_to_array(benefit_type, ','))"
Run Code Online (Sandbox Code Playgroud)

错误:

 Caused by:
PG::UndefinedFunction: ERROR:  function string_to_array(integer, unknown) does not exist
LINE 1: ...ALTER COLUMN "benefit_type" TYPE integer[] USING (string_to_...
                                                         ^
HINT:  No function matches the given name and argument types. You might need to add explicit 
type casts.
Run Code Online (Sandbox Code Playgroud)

还尝试过:

   change_column :providers, :benefit_type, :integer, array: true, default: []
Run Code Online (Sandbox Code Playgroud)

错误:

 Caused by:
ActiveRecord::StatementInvalid: PG::DatatypeMismatch: ERROR:  column "benefit_type" cannot 
be cast automatically to type integer[]
HINT:  You might need to specify "USING benefit_type::integer[]".
: ALTER TABLE "providers" ALTER COLUMN "benefit_type" TYPE integer[], ALTER COLUMN 
"benefit_type" SET DEFAULT '{}'
Run Code Online (Sandbox Code Playgroud)

Pra*_*tri 7

您需要在 using 关键字中指定带有列名的整数数组。

change_column :providers, :benefit_type, :integer, array: true, default: [], using: 'ARRAY[benefit_type]::INTEGER[]'
Run Code Online (Sandbox Code Playgroud)