###前提・実現したいこと
Userモデルを作成し、ログイン機能をdeviseで実装した後、Storageモデルで画像アップローダーを作ろうとしています。Storageモデルを作成して1対多の中間テーブルを作成するため、以下のようにuserをreferencesにしました。その後マイグレートを実施したところ、エラーが出てしまいました。
###発生している問題・エラーメッセージ
発生しているエラーは、
① ActiveRecord::StatementInvalid: Mysql2::Error: Table 'breakth_practice_6_development.storages' doesn't exist: SHOW FULL FIELDS FROM `storages` ② Mysql2::Error: Cannot add foreign key constraint
です。
###該当のソースコード
20170820235714_devise_create_users
class DeviseCreateUsers < ActiveRecord::Migration[5.1] def change create_table :users do |t| ## Database authenticatable t.string :email, null: false, default: "" t.string :encrypted_password, null: false, default: "" ## Recoverable t.string :reset_password_token t.datetime :reset_password_sent_at ## Rememberable t.datetime :remember_created_at ## Trackable t.integer :sign_in_count, default: 0, null: false t.datetime :current_sign_in_at t.datetime :last_sign_in_at t.string :current_sign_in_ip t.string :last_sign_in_ip ## Confirmable t.string :confirmation_token t.datetime :confirmed_at t.datetime :confirmation_sent_at t.string :unconfirmed_email # Only if using reconfirmable ## Lockable # t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts # t.string :unlock_token # Only if unlock strategy is :email or :both # t.datetime :locked_at t.timestamps null: false end add_index :users, :email, unique: true add_index :users, :reset_password_token, unique: true add_index :users, :confirmation_token, unique: true # add_index :users, :unlock_token, unique: true end end
20170821114819_create_storages.rb
class CreateStorages < ActiveRecord::Migration[5.1] def change create_table :storages do |t| t.references :user, foreign_key: true t.references :follow, foreign_key: true t.string :image t.string :subject t.integer :year t.timestamps end end end
###試したこと
色々調べたところ、mysqlで以下のコメントを打つと、現状のエラーの詳細がわかるというので打って見ました。おそらく参照される側のテーブルにindexがないということでしょうか?ただどうやって解決したら良いのかよくわかりません。もし分かる方がいたら教えていただけたらと思います。よろしくお願いします。
mysql>SHOW ENGINE INNODB STATUS;
LATEST FOREIGN KEY ERROR ------------------------ 2017-08-22 08:07:32 0x700004d0b000 Error in foreign key constraint of table breakth_practice_6_development/storages: FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) , CONSTRAINT `fk_rails_1833d48544` FOREIGN KEY (`follow_id`) REFERENCES `follows` (`id`) ) ENGINE=InnoDB: Cannot find an index in the referenced table where the referenced columns appear as the first columns, or column types in the table and the referenced table do not match for constraint. Note that the internal storage type of ENUM and SET changed in tables created with >= InnoDB-4.1.12, and such columns in old tables cannot be referenced by such columns in new tables. Please refer to http://dev.mysql.com/doc/refman/5.7/en/innodb-foreign-key-constraints.html for correct foreign key definition.
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/08/22 14:49
2017/08/22 22:53
2017/08/28 13:03
2017/08/28 14:21