Rails 迁移 - 在 rails 中将列类型从 float 更改为 jsonb

Rails migration - change column type from float to jsonb in rails

我试图在 rails 中将列类型从 float 转换为 jsonb。但它给出了这个错误。

 Caused by:
ActiveRecord::StatementInvalid: PG::CannotCoerce: ERROR:  cannot cast type double precision to json
LINE 1: ...es" ALTER COLUMN "quote_amounts" TYPE jsonb USING CAST(quote...
                                                             ^
: ALTER TABLE "vendor_quotes" ALTER COLUMN "quote_amounts" TYPE jsonb USING CAST(quote_amounts AS jsonb)

我已使用此迁移更改列类型

def change
    change_column :vendor_quotes, :quote_amounts, 'jsonb USING CAST(quote_amounts AS jsonb)'
  end

我尝试了其他语法,但仍然出现相同的错误。

没有从 double precisionjsonb 的默认转换(如您所见)。但是,有一个 to_jsonb function:

to_jsonb(anyelement)
Returns the value as json or jsonb. Arrays and composites are converted (recursively) to arrays and objects; otherwise, if there is a cast from the type to json, the cast function will be used to perform the conversion; otherwise, a scalar value is produced. For any scalar type other than a number, a Boolean, or a null value, the text representation will be used, in such a fashion that it is a valid json or jsonb value.

所以你应该可以说:

change_column :vendor_quotes, :quote_amounts, 'jsonb using to_jsonb(quote_amounts)'

change_column :vendor_quotes, :quote_amounts, :jsonb, using: 'to_jsonb(quote_amounts)'