データベースへ以下コードをマイグレーションファイルに記述し、実行したいのですが、エラーとなってしまいます。
・20210825062403_create_reservations.rb
t.references :user, null: false, foreign_key: true t.references :menu, null: false, foreign_key: true
エラーメッセージ
rails db:migrate == 20210825062403 CreateReservations: migrating =============================== -- create_table(:reservations) rails aborted! StandardError: An error has occurred, all later migrations canceled: Column `user_id` on table `reservations` 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 `reservations` to be :bigint. (For example `t.bigint :user_id`). Original message: Mysql2::Error: Cannot add foreign key constraint /Users/hosodayusuke/projects/original/db/migrate/20210825062403_create_reservations.rb:3:in `change' /Users/hosodayusuke/projects/original/bin/rails:9:in `<top (required)>' /Users/hosodayusuke/projects/original/bin/spring:15:in `<top (required)>' bin/rails:3:in `load' bin/rails:3:in `<main>' Caused by: ActiveRecord::MismatchedForeignKey: Column `user_id` on table `reservations` 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 `reservations` to be :bigint. (For example `t.bigint :user_id`). Original message: Mysql2::Error: Cannot add foreign key constraint /Users/hosodayusuke/projects/original/db/migrate/20210825062403_create_reservations.rb:3:in `change' /Users/hosodayusuke/projects/original/bin/rails:9:in `<top (required)>' /Users/hosodayusuke/projects/original/bin/spring:15:in `<top (required)>' bin/rails:3:in `load' bin/rails:3:in `<main>' Caused by: Mysql2::Error: Cannot add foreign key constraint /Users/hosodayusuke/projects/original/db/migrate/20210825062403_create_reservations.rb:3:in `change' /Users/hosodayusuke/projects/original/bin/rails:9:in `<top (required)>' /Users/hosodayusuke/projects/original/bin/spring:15:in `<top (required)>' bin/rails:3:in `load' bin/rails:3:in `<main>' Tasks: TOP => db:migrate (See full trace by running task with --trace)
・20210825062403_create_reservations.rb
class CreateReservations < ActiveRecord::Migration[6.0] def change create_table :reservations do |t| t.time :time, null: false t.date :date, null: false t.integer :people, null: false t.text :remark t.references :user, null: false, foreign_key: true t.references :menu, null: false, foreign_key: true t.timestamps end end end
試したこと
・ファイルの作成の順番を誤っているのかと思い確認。
→参照するファイルを先に作成しているため問題ないと考えられる。
・null:false 部分をtype: :bigintに修正
→同じエラー文が表示される
この他、考えられる原因をご教示いただけると幸いです。
どうぞ宜しくお願い致します。
ruby 2.6.5
Rails 6.0.4
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。