ruby on rails - Postgres: Default for column (string) cannot be cast automatically to type enum -


i have status column in table want enum. created field integer, thinking use built in rails enum functionality. turns out requires @ least rails 4.1, using 4.0 , process of upgrading going take time.

but thinking how works, realized can have either activerecord enum or postgres enum, not both. thought in long term having more explicit postgres enum best. so, wrote migration convert status column integer enum.

execute "create type status_options enum ('pending', 'declined', 'approved');" change_column :site_applications, :status, "status_options using status::status_options" 

but, error:

pg::cannotcoerce: error:  cannot cast type integer status_options alter table "site_applications" alter column "status" type status_options using status::status_options 

everything have seen far in searchings tells me should have worked, doesn't. thought maybe problem can't go integer enum. it. solution first convert column string , then try convert enum.

change_column :site_applications, :status, :string execute "create type status_options enum ('pending', 'declined', 'approved');" change_column :site_applications, :status, "status_options using status::status_options" 

and gives me following error:

pg::datatypemismatch: error:  default column "status" cannot cast automatically type status_options alter table "site_applications" alter column "status" type status_options using status::status_options 

that led me believe had default value, tried specifying default in change_column declaration:

change_column :site_applications, :status, :string, default: "pending" 

that changes column string default of "pending", change_column fails same "default column" error.

i realize drop column , recreate how want, @ point it's matter of posterity. why heck can't convert column integer or string enum? anyone?

update accepted answer

based on gary's answer down there, migration worked.

def   execute "alter table site_applications alter status drop default;"   execute "create type status_options enum ('pending', 'declined', 'approved');"   change_column :site_applications, :status, "status_options using status::status_options", default: "pending" end  def down   change_column :site_applications, :status, :string, default: "pending"   execute "drop type status_options;" end 

you need remove default value column prior change default set value valid old column type incompatible new type.

alter table schema.site_applications alter status drop default 

then can change column type. once new column type applied, can add new default against table.

alter table schema.site_applications alter status set default 'pending'::status_options 

Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -