0

I created a migration in my development to change the column type from integer to date in my client table.

Migration:

class UpdateGradToDate < ActiveRecord::Migration
  def change
    change_column :clients, :grad_id, :date
  end
end

Which worked fine in development. However, once I push it to Heroku, I got the following error message.

PG::DatatypeMismatch: ERROR:  column "grad_id" cannot be cast automatically to type date
HINT:  You might need to specify "USING grad_id::date".
: ALTER TABLE "clients" ALTER COLUMN "grad_id" TYPE date

I'm not sure how to correct this problem. I'm thinking perhaps using rails console and changing the column type there but I'm not sure if that's the best solution.

I also tried creating a new migration using using this syntax as well

class ChangeDateFormatInMyTable < ActiveRecord::Migration
  def up
   change_column :clients, :grad_id, :integer
  end

  def down
   change_column :clients, :grad_id, :date
  end
end

I'm not really sure what to do at this point.

1
  • How could grad_id possibly be a date? Why not just add a new column that makes sense as a date? Commented Jun 24, 2016 at 19:52

1 Answer 1

2

The issue here is clearly explained by the PostgreSQL error:

column "grad_id" cannot be cast automatically to type date

You are trying to convert a field that stores an integer, into a Date. The field could contain anything, including a value such as 10, 0 or -200. How those value could ever be converted into a Date?

What PostgreSQL is telling you is that you need to help him with the conversion.

Your best way is:

  1. rename grad_id into grad_id_legacy
  2. create a new grad_id Date field
  3. run a script that reads each value from grad_id_legacy and stores the corresponding, converted Date value into grad_id
Sign up to request clarification or add additional context in comments.

1 Comment

I would suggest reversing the order of your steps, i.e. create grad_id_date and then later rename it to grad_id, in order to minimize downtime. It's also possible to use a raw SQL ALTER TABLE statement with a USING clause to tell Postgres how to do the conversion, but it will lock the table for the duration of that process.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.