1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

デプロイ時のマイグレーションエラー Mysql2::Error: BLOB/TEXT column '〜' can't have a default value について

Posted at

Herokにアプリケーションをデプロイする際、
'heroku run rails db:migrate'でHeroku上でマイグレーションを実行しようとしたところ、

StandardError: An error has occurred, all later migrations canceled:


Mysql2::Error: BLOB/TEXT column 'profile' can't have a default value

というエラーが発生しました。今回はこのエラーの解決を行いたいと思います。

内容

マイグレーションの確認

まず、Heroku上でマイグレーションしようとした際に、エラーが生じたということは、マイグレーションファイルに何らかの問題があると想定されます。
そこで、 'rails db:migrate:srtatus' で現在のマイグレーションファイルの状況を確認します。

rails db:migrate:srtatus
=>
 Status   Migration ID    Migration Name
--------------------------------------------------
   up     20210211014935  Devise create users
   up     20210211120907  Create prototypes
   up     20210211125648  Create active storage tablesactive storage
   up     20210213030202  Create comments

全てアップですのでローカルのマイグレーションは問題ないと思われます。
一方で
'heroku run rails db:migrate:status' を実行すると、

 Status   Migration ID    Migration Name
--------------------------------------------------
D, [2021-02-15T02:04:37.398144 #4] DEBUG -- :    (2.1ms)  SELECT `schema_migrations`.`version` FROM `schema_migrations` ORDER BY `schema_migrations`.`version` ASC
  down    20210211014935  Devise create users
  down    20210211120907  Create prototypes
  down    20210211125648  Create active storage tablesactive storage
  down    20210213030202  Create comments

ダウンとなっております。

ローカル上のマイグレーションが問題なくても、Heroku上でマイグレーションが有効でない場合があります。

そのため、デプロイする際には、ローカルとHeroku両方でアプリケーションの挙動確認をする必要があるようです。
Herokuにアップする際は 'heroku run rails db:migrate:status' を行いましょう。

db/migrate内のファイルを確認

エラー文の2行目に注目します。
「'profile'カラムがデフォルト設定とすることができません」という内容のエラーです。

カラムについての記述は db/migrate のファイルを確認します。
devise_cerate_user.png
以下の defailt::"" が間違っているだろうと考えられます。

devise_cerate_user.rb
      t.text   :profile,            null: false, default: ""
      t.text   :occupation,         null: false, default: ""
      t.text   :position,           null: false, default: ""

こちらを

devise_cerate_user.rb
      t.text   :profile,            null: false
      t.text   :occupation,         null: false
      t.text   :position,           null: false

とします。
マイグレーションファイルを書き換えたので、rails db:rollbackしてから、rails db:migrateします。(今回はrails db:resetを行いました)

Githubに修正をpushしてから、再度、 'heroku run rails db:migrate’を実行。

うまく行きました。

総括
ローカル上のマイグレーションファイルが正常でも、Herokuにデプロイする際に無効となってしまうことがあります。
Herokuにアップする際は、忘れず ’heroku run rails db:migrate’を行い、ローカルとHeroku両方で挙動確認をしましょう。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?