MySQL2がbundle installできない

過去に作った簡単な個人アプリをherokuに上げてみよう、と色々なサイトを見ながら順調に進めていたのですが、いざデプロイの段階になってエラー。

エラー内容を見ているとその前にしたbundle installがうまくいっていない模様。

試しにrails sしてみたところ、エラーが出てできなかった。

読んでみるとmysql2がインストールできていないようだ。

$ bundle install
.
. # 省略
.
Installing ...
Fetching mysql2 0.5.2
Installing mysql2 0.5.2 with native extensions
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.
.
. # 省略
.
An error occurred while installing mysql2 (0.5.2), and Bundler cannot continue.
Make sure that `gem install mysql2 -v '0.5.2' --source 'https://rubygems.org/'` succeeds before bundling.

試してみたこと

1. エラー文の指示通りに下記を実行する

最後に書かれている通りgem install mysql2 -v '0.5.2' --source 'https://rubygems.org/'を試してみるがうまくいかない。

An error occurred while installing mysql2 (0.5.2), and Bundler cannot continue.
Make sure that `gem install mysql2 -v '0.5.2' --source 'https://rubygems.org/'` succeeds before bundling.

2. mysql2をアンインストール、再インストール

アンインストールはできたが再インストール時はやはり変わらず。

他、実はそもそもrails sができないエラーとして扱っていたため諸々の遠回りをしています。笑

解決方法

結果的に言うと以下のQiita記事を参考にしたら解決できました。

qiita.com

以下で設定する値を確認する

$ brew info openssl
openssl@1.1: stable 1.1.1f (bottled) [keg-only]
Cryptography and SSL/TLS Toolkit
https://openssl.org/
/usr/local/Cellar/openssl@1.1/1.1.1f (8,057 files, 18MB)
  Poured from bottle on 2020-04-09 at 17:43:55
From: https://github.com/Homebrew/homebrew-core/blob/master/Formula/openssl@1.1.rb
==> Caveats
A CA file has been bootstrapped using certificates from the system
keychain. To add additional certificates, place .pem files in
  /usr/local/etc/openssl@1.1/certs

and run
  /usr/local/opt/openssl@1.1/bin/c_rehash

openssl@1.1 is keg-only, which means it was not symlinked into /usr/local,
because macOS provides LibreSSL.

If you need to have openssl@1.1 first in your PATH run:
  echo 'export PATH="/usr/local/opt/openssl@1.1/bin:$PATH"' >> ~/.bash_profile

For compilers to find openssl@1.1 you may need to set:
  export LDFLAGS="-L/usr/local/opt/openssl@1.1/lib"
  export CPPFLAGS="-I/usr/local/opt/openssl@1.1/include"

For pkg-config to find openssl@1.1 you may need to set:
  export PKG_CONFIG_PATH="/usr/local/opt/openssl@1.1/lib/pkgconfig"

==> Analytics
install: 635,495 (30 days), 1,465,238 (90 days), 4,145,490 (365 days)
install-on-request: 89,713 (30 days), 202,425 (90 days), 582,112 (365 days)
build-error: 0 (30 days)

23,24行目を確認。

  export LDFLAGS="-L/usr/local/opt/openssl@1.1/lib"
  export CPPFLAGS="-I/usr/local/opt/openssl@1.1/include"

以下を実行。

$ bundle config --local build.mysql2 "--with-cppflags=-I/usr/local/opt/openssl/include"
$ bundle config --local build.mysql2 "--with-ldflags=-L/usr/local/opt/openssl/lib"

で、bundle install

$ bundle install

解決。安心。

LDFLAGSCPPFLAGSへの理解はまだできていない状態なので勉強していかないとなあ。