1

在我的Rails 5.0.5應用程序中,我需要將json列轉換爲string, array: truePostgreSQL不能將類型JSON轉換爲字符變化[]

json列中的值是這樣的:

[ "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[] 

我怎樣才能做到這一點的遷移?

回答

0

我猜數組元素是文件名。如果是這樣,那麼你就可以刪除所有的字符[]"和空格,結果拆到陣列,像這樣:

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[] 
相關問題