Rails 迁移以将列类型从文本更改为 json (Postgresql)

编程入门 行业动态 更新时间:2024-10-23 23:27:28
本文介绍了Rails 迁移以将列类型从文本更改为 json (Postgresql)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我一直在尝试将 Postgres 数据库中的列类型从文本更改为 json,但未成功.这是我尝试过的...

I've been trying unsuccessfully to change a column type in my Postgres database from text to json. Here's what I've tried...

class ChangeNotesTypeInPlaces < ActiveRecord::Migration[5.0] def up execute 'ALTER TABLE places ALTER COLUMN notes TYPE json USING (notes::json)' end def down execute 'ALTER TABLE places ALTER COLUMN notes TYPE text USING (notes::text)' end end

还有...

class ChangeNotesTypeInPlaces < ActiveRecord::Migration[5.0] def up change_column :places, :notes, 'json USING CAST(notes AS json)' end def down change_column :places, :notes, 'text USING CAST(notes AS text)' end end

这两个都返回相同的错误...

Both of these return the same error...

PG::InvalidTextRepresentation: ERROR: invalid input syntax for type json

推荐答案

使用 Rails 5.1.x 和 PostgreSQL 9.4,以下是将文本列(包含有效的 json)转换为 jsonb 列时对我有用的方法:

Using Rails 5.1.x and PostgreSQL 9.4, here is what worked for me when converting text columns (containing valid json) to jsonb columns :

class ChangeTextColumnsToJson < ActiveRecord::Migration[5.1] def change change_column :table_name, :column_name, :jsonb, using: 'column_name::text::jsonb' end end

更多推荐

Rails 迁移以将列类型从文本更改为 json (Postgresql)

本文发布于:2023-10-17 10:34:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1500662.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本   类型   Rails   json   Postgresql

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!