简体   繁体   中英

Rails 6.0 Migration file convert to integer as per Postgres preference?

Beginner here, deploying to Heroku. Sqlite3 in dev, PG in production.

Test environment has all migrations running successfully at this point.

I am trying to deploy to Heroku. The git works fine. But when I run heroku run rails db:migrate I get the following error

== 20210116010525 ChangeMediaLinksRefToInteger: migrating =====================
-- change_column(:media_links, :media_category_id, :integer)
D, [2021-01-16T19:33:04.056111 #4] DEBUG -- :    (1.4ms)  BEGIN
D, [2021-01-16T19:33:04.060684 #4] DEBUG -- :    (4.1ms)  ALTER TABLE "media_links" ALTER COLUMN "media_category_id" TYPE integer
D, [2021-01-16T19:33:04.066364 #4] DEBUG -- :    (5.0ms)  ROLLBACK
D, [2021-01-16T19:33:04.072867 #4] DEBUG -- :    (6.0ms)  SELECT pg_advisory_unlock(4856957400867515370)
rails aborted!
StandardError: An error has occurred, this and all later migrations canceled:

PG::DatatypeMismatch: ERROR:  column "media_category_id" cannot be cast automatically to type integer
HINT:  You might need to specify "USING media_category_id::integer".

Note: This migration was an error correction of my own making earlier where I accidentaly set the 'media_category_id' to be a string. I created this migration to change the column from string to integer. Migration file:

class ChangeMediaLinksRefToInteger < ActiveRecord::Migration[6.0]
  def change
    change_column :media_links, :media_category_id, :integer
  end
end

Can update this migration file or should I create a new one? Is this what Heroku is telling me to do?

class ChangeMediaLinksRefToInteger < ActiveRecord::Migration[6.0]
  def change
    change_column :media_links, "USING media_category_id::integer"
  end
end

Since your migration failed you can edit the migration to what Heroku recommended.

If the migration had ran successfully and you wanted to edit it, you could rollback the migration ./bin/rails db:rollback then edit the file, and then run the migrations again.

If you wanted to change a migration that is already deployed to a common test environment or to PreProd/Prod, then it is best to create a new migration to apply the changes on top.

This is what worked for me:

change_column :orders, :pay_type, "integer USING NULLIF(pay_type, '')::int"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM