ogirginc
ogirginc

Reputation: 5270

How to change_column in Rails from string to jsonb?

I tried to write a migration for an existing column in Rails 5.0.2:

def up
  change_column(:sales_deals, :lost_reason, 'jsonb USING CAST(lost_reason AS jsonb)')
end

def down
  change_column(:sales_deals, :lost_reason, 'string USING CAST(lost_reason AS string)')
end

However, failed to CAST existing string to jsonb:

PG::InvalidTextRepresentation: ERROR: invalid input syntax for type json
DETAIL: Token "Non" is invalid.
CONTEXT:  JSON data, line 1: Non...
: ALTER TABLE "sales_deals" ALTER COLUMN "lost_reason" TYPE jsonb USING CAST(lost_reason AS jsonb)

My guess is there are two problems:

1) I need to specify type of the value, because the token "Non" is a beginning of a string with hyphen, "Non-commutative".

2) I need to define a default key, because of the existing values.

Can anyone help please? Thanks!

Upvotes: 1

Views: 2095

Answers (1)

Amrinder Singh
Amrinder Singh

Reputation: 5502

You should try as follow:

  def up
    change_column :sales_deals, :lost_reason, :jsonb, using: 'CAST(value AS JSON)'
  end

  def down
    change_column :sales_deals, :lost_reason, :text
  end

That's it.

Upvotes: 1

Related Questions