こんにちは!kossyです!
さて、今回は、Rails5.2系で外部キーを設定しようとした時に遭遇したエラーについて、
ブログに残してみたいと思います。
エラーの状況
2019****_create_category.rb class CreateCategories < ActiveRecord::Migration[5.2] def change create_table :categories do |t| t.string :name, null: false t.text :content, null: false t.string :image, null: false t.timestamps end end end 2019****_create_article.rb class CreateArticles < ActiveRecord::Migration[5.2] def change create_table :articles do |t| t.string :title, null: false, index: true t.string :image t.text :description, null: false t.text :body, null: false t.integer :status, null: false t.references :user_id, foreign_key: true t.references :category_id, foreign_key: true t.timestamps end end end
この内容でrails db:migrateを実行してみると、
以下のエラーが発生しました。
rails aborted! StandardError: An error has occurred, all later migrations canceled: Mysql2::Error: Table 'cms_development.articles' doesn't exist: SHOW FULL FIELDS FROM `articles` Caused by: ActiveRecord::StatementInvalid: Mysql2::Error: Table 'cms_development.articles' doesn't exist: SHOW FULL FIELDS FROM `articles` Caused by: Mysql2::Error: Table 'cms_development.articles' doesn't exist Caused by: Mysql2::Error: Cannot add foreign key constraint
対処(ベストプラクティスかは怪しい)
外部キーを追加できないと怒られていたので、該当部分をコメントアウト
class CreateArticles < ActiveRecord::Migration[5.2] def change create_table :articles do |t| t.string :title, null: false, index: true t.string :image t.text :description, null: false t.text :body, null: false t.integer :status, null: false # t.references :user_id, foreign_key: true # t.references :category_id, foreign_key: true t.timestamps end end end
そして、rails db:migrateすると、ひとまず成功。
次に、
$ rails g migration AddReferencesToArticle user:references category:references 2019****_add_refereces_to_article.rb class AddReferenceToArticle < ActiveRecord::Migration[5.2] def change add_reference :articles, :user, foreign_key: true add_reference :articles, :category, foreign_key: true end end
この状態でrails db:migrateしたら、無事にreferenceカラムを追加できました。
これ本番環境でmigrationする時も起きるのでしょうか?
だとすれば、またそのうち対処法をブログに残すことになるかもしれません、、、笑
1/16 追記
t.references :user, foreign_key: true
t.references :category, foreign_key: true
とすればエラーは起きないみたいです、、、
もう同じミスはやらないと心に誓いました。