【问题标题】:Rails change existing text column to arrayRails 将现有文本列更改为数组
【发布时间】:2017-05-03 07:27:22
【问题描述】:

使用 Postgres 数据库,将文本字段 staff_ids 添加到 branches 表中:

add_column :branches, :staff_ids, :text

在控制器中将此字段添加到 branch_params 列表中:

:staff_ids => []

数据已保存在此列中,例如["","32","52"]。查询此字段时,我收到一条错误消息,提示 staff_ids 应该是一个数组

Branch.where("? = ANY(staff_ids)", '20')

ActiveRecord::StatementInvalid: PG::WrongObjectType: ERROR:  op ANY/ALL (array) requires array on right side

实际上,我在添加staff_ids 字段时忘记在迁移中添加array: true 选项。 现在添加了另一个迁移来更改此列并尝试添加array: true 选项:

change_column :branches, :staff_ids, :text, array: true

但迁移失败并出现错误:

PG::DatatypeMismatch: ERROR:  column "staff_ids" cannot be cast automatically to type text[]

现在要么我想更新 where 子句,以便它根据 staff_ids 过滤分支而不添加数组:true 要么修复上面提到的迁移。

有什么建议/想法吗?

【问题讨论】:

标签: ruby-on-rails postgresql


【解决方案1】:

您可以在迁移中添加以下内容,

def up
    change_column :branches, :staff_ids, :text, array: true, default: [], using: "(string_to_array(staff_ids, ','))"
end

def down
    change_column :branches, :staff_ids, :text, array: false, default: nil, using: "(array_to_string(staff_ids, ','))"
end

如果不需要更改数组,定义 up 和 down 方法将有助于随时逆转您的迁移。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-09
    • 1970-01-01
    相关资源
    最近更新 更多