在我的Rails 5.0.5应用程序中,我需要将json列转换为string, array: true
myjson列中的值如下:

[ "200px-RR5219-0015R.png", "2017_03_25_2235.doc", "137555.jpg" ]

我试过这个迁移:
class ChangeTaskAttachmentsTypeToString < ActiveRecord::Migration[5.0]
  def change
    change_column :tasks, :attachments, :string, array: true
  end
end

得到这个错误:
ActiveRecord::StatementInvalid: PG::DatatypeMismatch: ERROR:  column "attachments" cannot be cast automatically to type character varying[]
HINT:  You might need to specify "USING attachments::character varying[]".
: ALTER TABLE "tasks" ALTER COLUMN "attachments" TYPE character varying[]

然后我编辑了迁移:
class ChangeTaskAttachmentsTypeToString < ActiveRecord::Migration[5.0]
  def change
    change_column :tasks, :attachments, 'character varying[] USING attachments::character varying[]'
  end
end

最后得到这个错误:
PG::CannotCoerce: ERROR:  cannot cast type json to character varying[]
: ALTER TABLE "tasks" ALTER COLUMN "attachments" TYPE character varying[] USING attachments::character varying[]

我怎样才能做这个迁移?

最佳答案

我猜数组元素是文件名。如果是,则可以删除所有字符[]"和空格,并将结果拆分为数组,如下所示:

with my_table(attachments) as (
values
    ('[ "200px-RR5219-0015R.png", "2017_03_25_2235.doc", "137555.jpg" ]'::json)
)
select string_to_array(translate(attachments::text, '[] "', ''), ',')::varchar[]
from my_table;

                     string_to_array
---------------------------------------------------------
 {200px-RR5219-0015R.png,2017_03_25_2235.doc,137555.jpg}
(1 row)

所以使用:
... USING string_to_array(translate(attachments::text, '[] "', ''), ',')::varchar[]

10-07 20:33