rails tutorial 14章で詰まった話
rails tutorial14章でrelationshipを扱っていたとき、seedデータを追加するときに
UNIQUE constraint failed: relationships.follower_id rails tutorial
というエラーに悩まされた 最初はデータベースがバグってるのかと思いreset等をいろいろ したが、どうもうまくいかない。
真面目にエラー文を見て、ユニーク制約で変なものを追加していないか確認するためにrelationshipsテーブルを作ったときのmigrationファイルを見たら、
class CreateRelationships < ActiveRecord::Migration[5.1] def change create_table :relationships do |t| t.integer :follower_id t.integer :followed_id t.timestamps end add_index :relationships, :follower_id add_index :relationships, :followed_id add_index :relationships, [:follower_id, :follower_id], unique: true # ここ end end
と書いてあった。unique制約が follower_id, followed_idとするところを間違えてる。
migrationを巻き戻そうとdb:rollbackを試すも
StandardError: An error has occurred, this and all later migrations canceled: No indexes found on relationships with the options provided.
と言われる
db:resetとかしたからいけないんかな、?とか思いつつ、いろいろ調べる
indexがない?よくわからんけど remove_indexする投稿を見つけたのでそれもmigrationファイル書いてみる。
StandardError: An error has occurred, this and all later migrations canceled: No indexes found on relationships with the options provided.
なんと同じエラー
わからん
幸い今回はtutorialということでDBは何度でも短時間でリセットできる。
問題のmigrationをreset した上でDBを作り直してみる(本当にそういう操作をしているか確証はないが)
rails db:drop && rails db:create && rails db:schema:load
再度同じエラー。 schema.rbにDBの情報書いてあるから、そこからloadしたら意味ないのでは?と思ってschema.rbを試しに消してからmigrateしてみる
rails db:drop && rails db:create rails db:migrate
無事seeds.rbも生成された上で直った。