Ruby on rails PostgreSQL可以';将json类型转换为字符变化[]
在我的Rails 5.0.5应用程序中,我需要将Ruby on rails PostgreSQL可以';将json类型转换为字符变化[],ruby-on-rails,postgresql,ruby-on-rails-5,postgresql-9.3,rails-migrations,Ruby On Rails,Postgresql,Ruby On Rails 5,Postgresql 9.3,Rails Migrations,在我的Rails 5.0.5应用程序中,我需要将json列转换为string,array:true myjson列中的值如下所示: [ "200px-RR5219-0015R.png", "2017_03_25_2235.doc", "137555.jpg" ] 我尝试了这种迁移: class ChangeTaskAttachmentsTypeToString
json
列转换为string,array:true
myjson
列中的值如下所示:
[ "200px-RR5219-0015R.png", "2017_03_25_2235.doc", "137555.jpg" ]
我尝试了这种迁移:
class ChangeTaskAttachmentsTypeToString
得到了这个错误:
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[]
PG::CannotCoerce: ERROR: cannot cast type json to character varying[]
: ALTER TABLE "tasks" ALTER COLUMN "attachments" TYPE character varying[] USING attachments::character varying[]
然后我编辑了迁移:
class ChangeTaskAttachmentsTypeToString
最后得到了这个错误:
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[]
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[]