はじめに
最近、Railsを触り始めました。
転職先で使用するかもしれないので学習するためにはじめてます。
(この時はまだ決まってない。この先も決まらない…かも…しれない )
今回は自分が遭遇したエラー対応の備忘録として書いてます。
環境
- Ruby 3.2.3
- Rails 7.1.3
- SQLite3 1.4
rails test
したら、'Migrations are pending.' と出る
rails test
コマンドを実行しようとしたら、以下のエラーが出る。
C:\Users> rails test
Migrations are pending. To resolve this issue, run:
bin/rails db:migrate
You have 2 pending migrations:
db/migrate/20240227131218_create_users.rb
db/migrate/20240302042818_create_microposts.rb
Migrations are pending.
→ " マイグレーションが保留中です。 "
※ Google翻訳です
保留中?ようわからん。
マイグレーションがなんか、途中的な感じ?
マイグレーションの状況を見てみよう
じゃあ、rails db:migrate:status
でマイグレーションの状態見てみよう。
C:\Users> rails db:migrate:status
database: storage/development.sqlite3
Status Migration ID Migration Name
--------------------------------------------------
up 20240227131218 Create users
up 20240302042818 Create microposts
どちらも状態は"up"なので、問題なさそう。
解決策も提示されていたが...
もう一度、エラー内容を見てみると
「この問題を解決するには rails db:migrate
してね。」
みたいなことを仰っております。
C:\Users> rails test
Migrations are pending. To resolve this issue, run:
bin/rails db:migrate
:
でも、rails db:migrate
や rails db:reset
→ rails db:migrate
しても治らない...
rails db:setup
で治った
rails db:setup --trace
で解決しました。
C:\Users> rails db:setup --trace
** Invoke db:setup (first_time)
** Invoke db:create (first_time)
** Invoke db:load_config (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute db:load_config
** Execute db:create
Database 'storage/development.sqlite3' already exists
Database 'storage/test.sqlite3' already exists
** Invoke environment
** Invoke db:schema:load (first_time)
** Invoke db:load_config
** Invoke db:check_protected_environments (first_time)
** Invoke db:load_config
** Execute db:check_protected_environments
** Execute db:schema:load
** Invoke db:seed (first_time)
** Invoke db:load_config
** Execute db:seed
** Invoke db:abort_if_pending_migrations (first_time)
** Invoke db:load_config
** Execute db:abort_if_pending_migrations
** Execute db:setup
rails test
コマンドも動作しました!
rails db:setup
はDBを設定するもの
コマンド実行後、
「データベースの作成」、「スキーマの読み込み」、「seedデータでのDBデータ初期化」
をやってくれるコマンドみたい。
DBが既にあっても同じ手順を踏む?
似たもので rails db:prepare
コマンドは既にDBがあるかどうかを気にするみたいだけど
rails db:setup
は気きにしないのか…な?(だとしたら安易にコマンド叩かない方がいい)
おわりに
自分の場合は今回、DBからおかしかったのだろう
だから、rails db:migrate
でテーブルをどうこうしても治らなかったのかな
参考資料