How to change field type in Ecto?

14,122

You have to use modify/3 to change the type. add/3 is only for adding new columns.

alter table(:editables) do
  modify :content, :binary
end
Share:
14,122

Related videos on Youtube

Paulo Janeiro
Author by

Paulo Janeiro

Updated on February 12, 2020

Comments

  • Paulo Janeiro
    Paulo Janeiro about 4 years

    I have a schema:

    schema "editables" do
        field :title, :string
        field :content, :string
    
        timestamps
      end
    

    Now I want to change the type of one field form :integer to :binary. What's the correct way of writing the migration because using add is not working...?

    def change do
        alter table(:editables) do
          add :title, :binary
          add :content, :binary
    
          timestamps
        end
      end
    
  • Paulo Janeiro
    Paulo Janeiro over 8 years
    but now i'm getting this error: ERROR (datatype_mismatch): column "title" cannot be cast automatically to type bytea
  • Gazler
    Gazler over 8 years
    @PauloJaneiro If you can delete your database then deleting and recreating will fix it. The problem is that it won't be able to automatically migrate the type.
  • Gazler
    Gazler over 8 years
    @PauloJaneiro be sure to update your schema in your model too.
  • Paulo Janeiro
    Paulo Janeiro over 8 years
    Right. So this cannot be done when in production...Thanks Gazler.
  • Gazler
    Gazler over 8 years
    One of your records will be causing the issue with incompatible data (maybe NULLs?) Check out postgresql.org/message-id/… - it can be done but not with the Ecto migration DSL.
  • Jonathan Soifer
    Jonathan Soifer almost 7 years
    In my case I successfully migrated from :string to :text but I had to restart the server afterwards. I was getting a weird PostgreSQL error.