Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.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 Postgres DB列类型转换_Ruby On Rails_Ruby_Database_Postgresql_Migration - Fatal编程技术网

Ruby on rails Postgres DB列类型转换

Ruby on rails Postgres DB列类型转换,ruby-on-rails,ruby,database,postgresql,migration,Ruby On Rails,Ruby,Database,Postgresql,Migration,正在尝试将字符串列转换为日期。列当前保存值,例如“20170130”和“20161130” 当我尝试时: change_column :tickets, :string_date, :date 这给了我一个错误: 因此,我尝试: change_column :tickets, :string_date, 'date USING CAST(string_date AS date)' 仍然不走运,出现以下错误: PG::InvalidDatetimeFormat:错误:日期类型的输入语法无效 有

正在尝试将字符串列转换为日期。列当前保存值,例如“20170130”和“20161130”

当我尝试时:

change_column :tickets, :string_date, :date
这给了我一个错误:

因此,我尝试:

change_column :tickets, :string_date, 'date USING CAST(string_date AS date)'
仍然不走运,出现以下错误:

PG::InvalidDatetimeFormat:错误:日期类型的输入语法无效

有人知道发生了什么吗??认为从字符串转换为日期会更容易


提前感谢

奇怪-我希望看到值,如果您未能选择日期,例如:

t=# create table a2(string_date text);
CREATE TABLE
t=# insert into a2 values ('20170130'),('20161130');
INSERT 0 2
t=# insert into a2 select 'bad value';
INSERT 0 1
t=# alter table a2 alter COLUMN string_date type date using string_date::date;
ERROR:  invalid input syntax for type date: "bad value"
也许是一个空字符串

无论如何-找到错误值并修复它,然后再次尝试转换:

t=# select string_date from a2 where string_date !~ '\d{8}';
 string_date
-------------
 bad value
(1 row)
t=# begin;
BEGIN
t=# delete from a2 where string_date !~ '\d{8}';
DELETE 1
t=# alter table a2 alter COLUMN string_date type date using string_date::date;
ALTER TABLE
t=# end;
COMMIT

这对我帮助很大!谢谢结果是有一个坏记录(呸,真不敢相信我以前没有注意到)。我删除了坏记录,砰,就这样!谢谢
t=# select string_date from a2 where string_date !~ '\d{8}';
 string_date
-------------
 bad value
(1 row)
t=# begin;
BEGIN
t=# delete from a2 where string_date !~ '\d{8}';
DELETE 1
t=# alter table a2 alter COLUMN string_date type date using string_date::date;
ALTER TABLE
t=# end;
COMMIT