LoginSignup
9
3

More than 1 year has passed since last update.

Homebrewを入れ直ししたらrails g scaffoldでつまづく理屈を調べてみた

Last updated at Posted at 2022-10-07

自分の覚書として残します。

環境

OS macOS 12.3.1(M1チップ)
Ruby 3.0.1
Rails 6.1.6
Postgresql 14.5

経緯

$ rails g scaffold 〜

を実行したところ、エラー発生。

/Users/user_name/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/bootsnap-1.13.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:32:in `require': dlopen(/Users/user_name/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/pg-1.4.3/lib/pg_ext.bundle, 0x0009): Library not loaded: '/usr/local/opt/postgresql/lib/libpq.5.dylib'
  Referenced from: '/Users/user_name/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/pg-1.4.3/lib/pg_ext.bundle'
  Reason: tried: '/usr/local/opt/postgresql/lib/libpq.5.dylib' (no such file), '/usr/local/lib/libpq.5.dylib' (no such file), '/usr/lib/libpq.5.dylib' (no such file) - /Users/user_name/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/pg-1.4.3/lib/pg_ext.bundle (LoadError)

解決への道のり

まず注目したのが、以下のパス。

/usr/local/opt/postgresql/lib/libpq.5.dylib (no such file)
/usr/local/lib/libpq.5.dylib (no such file)

いずれも /user/local/ を見にいって no such file と言われて失敗している。
なぜこのパスを見にいっているのか?

1. これってあれかも?

気づいたのが、Homebrewのこと。
私はM1 macbookを使っていますが、Intelチップモードでターミナルを起動したままHomebrewをインストールしたことがありました。その結果、 /usr/local/ 配下にインストールされたHomebrewで、Rubyをはじめ、RailsやPostgreSQLなどもインストール。
途中で気づき、ターミナルをM1チップモードに切り替えて、Homebrewを入れ直ししたことがあったのです。

今回のエラーメッセージに出てくる /user/local/ とは、この名残では?

2. 仮説を立ててみた

エラーメッセージにある

Referenced from: '/Users/user_name/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/pg-1.4.3/lib/pg_ext.bundle'

というメッセージから、以下のような仮説を立てました。

  • Referenced from とあるように、 pg_ext.bundle という(謎の)ファイルが、見に行くパス情報を持っているのではないか。
  • このgemは、Homebrewが /user/local/ 配下にある時にインストールしたgem。だから、 /user/local/ のパスを見にいこうとしているではないか。
  • であれば、Homebrewが /user/local/ 配下にある時にインストールしたgemを入れ直しをすれば解決するのではないか。

3. 検証してみた

①rbenvを削除
②しかし、ディレクトリはそのまま残っていた
③パス情報を持っているファイルが残っているといけないので、 .rbenv ディレクトリごと削除
スクリーンショット 2022-10-07 11.10.34.png

その上で、

$ brew install rbenv ruby-build

から始まり、Ruby、PostgreSQL、Railsをインストール。

その結果、当初のエラーは発生しなくなりました。

4. もっと簡単に解決する方法があった

@uasiさんからいただいたコメント にあるように、

$ bundle pristine

を実行すれば、.rbenv ディレクトリごとの削除などは不要だったようです。
こんなコマンド、知らなかった!
@uasi さん、ありがとうございました!

9
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
3