Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails将现有文本列更改为数组_Ruby On Rails_Postgresql - Fatal编程技术网

Ruby on rails Rails将现有文本列更改为数组

Ruby on rails Rails将现有文本列更改为数组,ruby-on-rails,postgresql,Ruby On Rails,Postgresql,使用Postgres数据库,将文本字段staff\u id添加到branchs表中: add_column :branches, :staff_ids, :text 在控制器中,将此字段添加到分支参数列表: :staff_ids => [] 数据已保存在此列中,如[“”、“32”、“52”]。当查询这个字段时,我得到一个错误,说staff_id应该是一个数组 Branch.where("? = ANY(staff_ids)", '20') ActiveRecord::Statemen

使用Postgres数据库,将文本字段
staff\u id
添加到
branchs
表中:

add_column :branches, :staff_ids, :text
在控制器中,将此字段添加到分支参数列表:

:staff_ids => []
数据已保存在此列中,如
[“”、“32”、“52”]
。当查询这个字段时,我得到一个错误,说staff_id应该是一个数组

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

ActiveRecord::StatementInvalid: PG::WrongObjectType: ERROR:  op ANY/ALL (array) requires array on right side
实际上,在添加
staff\u id
字段时,我忘了在迁移中添加
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_id过滤分支,而不添加array:true,要么修复上面提到的迁移


有什么建议/想法吗

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

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方法将有助于随时逆转迁移。

您可以尝试在db级别使用SQL进行修复,但是您可能想要修复迁移?。要在迁移中修复它以便在登台和生产环境中执行它,您可以在迁移中运行该答案中的代码。