Reputation: 109
I am trying to convert column type from float to jsonb in rails. but it is giving this error.
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)
I have used this migration to change the column type
def change
change_column :vendor_quotes, :quote_amounts, 'jsonb USING CAST(quote_amounts AS jsonb)'
end
I have tried other syntax but still ends up with the same error.
Upvotes: 0
Views: 1078
Reputation: 434685
There is no default cast from double precision
to jsonb
(as you've found). However, there is a to_jsonb
function:
to_jsonb(anyelement)
Returns the value asjson
orjsonb
. Arrays and composites are converted (recursively) to arrays and objects; otherwise, if there is a cast from the type tojson
, 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 validjson
orjsonb
value.
So you should be able to say:
change_column :vendor_quotes, :quote_amounts, 'jsonb using to_jsonb(quote_amounts)'
or
change_column :vendor_quotes, :quote_amounts, :jsonb, using: 'to_jsonb(quote_amounts)'
Upvotes: 4