我status
在表中有一列我想成为枚举.最初我将该字段创建为整数,认为我将使用内置的Rails枚举功能.事实证明,至少需要Rails 4.1,但我使用4.0并且升级过程需要一些时间.
但想着这一切是如何工作的,我意识到,我可以有任何一个ActiveRecord枚举或一个Postgres枚举,而不是两个.我认为从长远来看,有更明确的postgres枚举是最好的.所以,我编写了一个迁移来将status
列从整数转换为枚举.
execute "CREATE TYPE status_options AS ENUM ('pending', 'declined', 'approved');"
change_column :site_applications, :status, "status_options USING status::status_options"
Run Code Online (Sandbox Code Playgroud)
但是,我收到此错误:
PG::CannotCoerce: ERROR: cannot cast type integer to status_options
ALTER TABLE "site_applications" ALTER COLUMN "status" TYPE status_options USING status::status_options
Run Code Online (Sandbox Code Playgroud)
到目前为止,我在搜索中看到的所有内容都告诉我应该有效,但事实并非如此.我想也许问题是我不能从整数到枚举.就这样吧.我的解决方案是首先将列转换为字符串,然后尝试将其转换为枚举.
change_column :site_applications, :status, :string
execute "CREATE TYPE status_options AS ENUM ('pending', 'declined', 'approved');"
change_column :site_applications, :status, "status_options USING status::status_options"
Run Code Online (Sandbox Code Playgroud)
这给了我以下错误:
PG::DatatypeMismatch: ERROR: default for column "status" cannot be cast automatically …
Run Code Online (Sandbox Code Playgroud)