【问题标题】:Change column type from text to array of string (PG::DatatypeMismatch: ERROR: column)将列类型从文本更改为字符串数组 (PG::DatatypeMismatch: ERROR: column)
【发布时间】:2020-08-06 10:36:13
【问题描述】:

我想将列类型从文本更改为字符串数组,所以我使用此迁移

class ChangeEmailsAndPhonesToArrayOfString < ActiveRecord::Migration[6.0]
  def up
    change_table :hotels do |t|
      t.change :emails, :string, array: true, default: []
      t.change :phones, :string, array: true, default: []
    end
  end

  def down
    change_table :hotels do |t|
      t.change :emails, :text
      t.change :phones, :text
    end
  end
end

但是当我运行 rails db:migrate 时出现此错误

PG::DatatypeMismatch: ERROR: column "emails" cannot be cast to type character varying[] 提示:您可能需要指定“USING emails::character varying[]”。

我该如何解决这个问题?

【问题讨论】:

标签: ruby-on-rails ruby


【解决方案1】:

正如错误文本所指定的,您必须指定强制转换才能在迁移中进行此数据类型更改。

你可以像下面这样使用它:

class ChangeEmailsAndPhonesToArrayOfString < ActiveRecord::Migration
  def up
    change_table :hotels do |t|
      t.change :emails, 'text ARRAY USING emails::character varying[]', default: []
      t.change :phones, 'text ARRAY USING phones::character varying[]', default: []
    end
  end

  def down
    change_table :hotels do |t|
      t.change :emails, :text
      t.change :phones, :text
    end
  end
end

在上面的示例中,我们为给定字段指定了一个显式转换为text[] 类型。

但是,您可能必须在表中显式转换数据(如果有)。

【讨论】:

    【解决方案2】:

    根据link,以下代码适用于我

    def up
      change_table :hotels do |t|
        t.change :emails, :string, array: true, default: [], using: "(string_to_array(emails, ','))"
        t.change :phones, :string, array: true, default: [], using: "(string_to_array(phones, ','))"
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-28
      • 2022-09-25
      • 2014-07-19
      • 1970-01-01
      • 2015-08-02
      • 1970-01-01
      • 2021-02-27
      • 2023-03-20
      相关资源
      最近更新 更多