ume

Rails 6でテーブルカラムの型不一致による外部キー追加エラーが発生した場合の解決方法

エラー経緯

rails tutorial13章を始め新しいカラム追加しようと以下のコマンドを実行しました

rails generate model Micropost content:text user:references

その後

 rails db:migrate

dbに反映させようとすると以下のエラーが出力されました。

rake aborted!
StandardError: An error has occurred, all later migrations canceled:

Column `user_id` on table `microposts` does not match column `id` on `users`, which has type `bigint(20)`. To resolve this issue, change the type of the `user_id` column on `microposts` to be :bigint. (For example `t.bigint :user_id`).

意味はデータの型が一致していない。 簡単にいうと Aというテーブルのカラム(user_id)とBというテーブルのカラム(id)のデータの型は一致しないとダメなのに一致していないということでエラーが出力された。

解決策

マイグレーションファイルの一番上に記載されている

class CreateMicroposts < ActiveRecord::Migration[5.1] ⇦ここ
  def change
    create_table :microposts do |t|
      t.text :content
      t.references :user, null: false,foreign_key: true

      t.timestamps
    end
    add_index :microposts, [:user_id, :created_at]
  end
end
変更前 Migration[5.0]
変更後 Migration[5.1]

これでうまくいきました。