Ruby on rails Rails将现有文本列更改为数组
使用Postgres数据库,将文本字段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
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进行修复,但是您可能想要修复迁移?。要在迁移中修复它以便在登台和生产环境中执行它,您可以在迁移中运行该答案中的代码。