【问题标题】:Rails migration to change column type from text to json (Postgresql)Rails 迁移以将列类型从文本更改为 json (Postgresql)
【发布时间】:2018-02-19 01:52:28
【问题描述】:

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

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

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

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

【问题讨论】:

  • notes 列是否已经有一个不是有效 json 的值?
  • 这是个好问题。我从来没有在这个列中保存过数据(在开发中,不幸的是在生产中不是同样的情况),但我也没有对该列的非空约束。可能是它一直在将一个空字符串保存到导致这种情况的列中吗?如果是,你知道我该如何解决这个问题吗?
  • 如果你没有非空约束,那么空值就可以了,或者你可以保存空 json {}。它不接受空字符串。

标签: ruby-on-rails postgresql rails-migrations


【解决方案1】:

使用 Rails 5.1.x 和 PostgreSQL 9.4,在将文本列(包含有效 json)转换为 jsonb 列时,这对我有用:

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

【讨论】:

  • 这在 postgres 9.6 rails 5.1 中工作,我必须添加相反的内容:def down change_column :table_name, :column_name, :text end
【解决方案2】:

我能够使用:

def change
  change_column :places, :notes, :json, using: 'notes::JSON'
end

但这不会是可逆的;我想你可以把它分成单独的上下定义,但我觉得没有必要。

【讨论】:

  • 应该将updown分开。
【解决方案3】:

我刚刚解决了一个类似的问题。尝试根据您的问题对其进行调整,它看起来(大部分?)是这样的。

class ChangeNotesTypeInPlaces < ActiveRecord::Migration[5.0]
  def up
    change_column :places, :notes, :jsonb, using: 'CAST(value AS JSON)'
  end

  def down
    change_column :places, :notes, :text
  end
end

【讨论】:

  • 如果 CAST 中的“价值”一词被替换为“笔记”,则对我有用
猜你喜欢
  • 1970-01-01
  • 2020-06-09
  • 1970-01-01
  • 2023-02-09
  • 2023-03-27
  • 2016-10-09
  • 2016-09-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多