Dhruvil Dave
Dhruvil Dave

Reputation: 109

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

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

Answers (1)

mu is too short
mu is too short

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 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.

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

Related Questions