プログラミング初学者なしこの技術アウトプット

プログラミングスクールRUNTEQで学んだことや自習したことのアウトプットをするブログ

rails db:migrateしたらMysql2::Error::ConnectionError: Can't connect to local MySQL server through socket ‘/tmp/mysql.sock'とエラーが出る

sorceryを導入する手順の途中でrails db:migrateしたらMysql2::Error::ConnectionError: Can't connect to local MySQL server through socket ‘/tmp/mysql.sock'とエラーが出ました。

※sorceryの導入方法 ( gem sorceryを使ってログイン機能を実装した話 - Qiita )

以下のサイトを参考に解決に導けました! qiita.com

私の場合、 以下手順でエラーを解決できました。

手順

#mysql.sockというMySQLへ接続するためのファイルをもう一度作成
% sudo touch /tmp/mysql.sock

#作ったsockファイルをちゃんとtmp下にファイルをしまってあげる
% sudo chown mysql:mysql /tmp

#ファイルのあるディレクトリに対する権限を付与
% sudo chown -R _mysql:_mysql /usr/local/var/mysql

#MySQLを再起動すると成功!
% sudo mysql.server restart
Starting MySQL
.. SUCCESS! 


ちなみに、その後、再度sorcery導入のためrails db:migrateをしたらActiveRecord::NoDatabaseError: Unknown database 'アプリ名_development'とエラーが出ました。
こちらはrails db:createを最初に打つことを忘れていてデータベース自体が作成されていないためでした。 ( ActiveRecord::NoDatabaseError: Unknown database 'アプリ名_development' 解決策 - Qiita )

以下の違いを再確認しました!
rails db:create → データベース自体(テーブルを保管しておく全体のシステム)を作るときに使うコマンド
rails db:migrate → は、データベースの中にテーブルを作ったり、カラムを変更したりするときに実行するコマンド

rails -vやrails sでincompatible library versionとエラーが出る

アプリ作成の初期段階で、以下コマンドを完了した後、rails -vやrails sをしたところincompatible library versionとエラーが出た為、解決方法を残しておきます。

完了したコマンド

$ bundle init
$ Gemfile内に以下を記載

ruby '2.6.4'
gem 'rails', '~> 5.2.6'

$ bundle install --path vendor/bundle
$ bundle exec rails new . -d mysql --skip-coffee --skip-turbolinks
$ git add .
$ git commit -m "initial commit"
$ git flow init
$ git push --all
$ git flow feature start 01_hogehogebranch

エラーコード

% rails -v
Traceback (most recent call last):
        15: from bin/rails:3:in `<main>'
        14: from bin/rails:3:in `require_relative'
        13: from /Users/xxxxxxxxxx/workspace/insta_clone/config/boot.rb:4:in `<top (required)>'
        12: from /Users/xxxxxxxxxx/workspace/insta_clone/config/boot.rb:4:in `require'
        11: from /Users/xxxxxxxxxx/workspace/insta_clone/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap/setup.rb:2:in `<top (required)>'
        10: from /Users/xxxxxxxxxx/workspace/insta_clone/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap/setup.rb:2:in `require_relative'
         9: from /Users/xxxxxxxxxx/workspace/insta_clone/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap.rb:5:in `<top (required)>'
         8: from /Users/xxxxxxxxxx/workspace/insta_clone/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap.rb:5:in `require_relative'
         7: from /Users/xxxxxxxxxx/workspace/insta_clone/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap/load_path_cache.rb:61:in `<top (required)>'
         6: from /Users/xxxxxxxxxx/workspace/insta_clone/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap/load_path_cache.rb:61:in `require_relative'
         5: from /Users/xxxxxxxxxx/workspace/insta_clone/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap/load_path_cache/store.rb:4:in `<top (required)>'
         4: from /Users/xxxxxxxxxx/workspace/insta_clone/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap/explicit_require.rb:41:in `with_gems'
         3: from /Users/xxxxxxxxxx/workspace/insta_clone/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap/load_path_cache/store.rb:4:in `block in <top (required)>'
         2: from /Users/xxxxxxxxxx/workspace/insta_clone/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap/load_path_cache/store.rb:4:in `require'
         1: from /Users/xxxxxxxxxx/workspace/insta_clone/vendor/bundle/ruby/2.6.0/gems/msgpack-1.4.2/lib/msgpack.rb:8:in `<top (required)>'
/Users/xxxxxxxxxx/workspace/insta_clone/vendor/bundle/ruby/2.6.0/gems/msgpack-1.4.2/lib/msgpack.rb:8:in `require': incompatible library version - /Users/xxxxxxxxxx/workspace/insta_clone/vendor/bundle/ruby/2.6.0/gems/msgpack-1.4.2/lib/msgpack/msgpack.bundle (LoadError)
        16: from bin/rails:3:in `<main>'
        15: from bin/rails:3:in `require_relative'
        14: from /Users/xxxxxxxxxx/workspace/insta_clone/config/boot.rb:4:in `<top (required)>'
        13: from /Users/xxxxxxxxxx/workspace/insta_clone/config/boot.rb:4:in `require'
        12: from /Users/xxxxxxxxxx/workspace/insta_clone/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap/setup.rb:2:in `<top (required)>'
        11: from /Users/xxxxxxxxxx/workspace/insta_clone/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap/setup.rb:2:in `require_relative'
        10: from /Users/xxxxxxxxxx/workspace/insta_clone/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap.rb:5:in `<top (required)>'
         9: from /Users/xxxxxxxxxx/workspace/insta_clone/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap.rb:5:in `require_relative'
         8: from /Users/xxxxxxxxxx/workspace/insta_clone/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap/load_path_cache.rb:61:in `<top (required)>'
         7: from /Users/xxxxxxxxxx/workspace/insta_clone/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap/load_path_cache.rb:61:in `require_relative'
         6: from /Users/xxxxxxxxxx/workspace/insta_clone/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap/load_path_cache/store.rb:4:in `<top (required)>'
         5: from /Users/xxxxxxxxxx/workspace/insta_clone/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap/explicit_require.rb:40:in `with_gems'
         4: from /Users/xxxxxxxxxx/workspace/insta_clone/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap/explicit_require.rb:44:in `rescue in with_gems'
         3: from /Users/xxxxxxxxxx/workspace/insta_clone/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap/load_path_cache/store.rb:4:in `block in <top (required)>'
         2: from /Users/xxxxxxxxxx/workspace/insta_clone/vendor/bundle/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap/load_path_cache/store.rb:4:in `require'
         1: from /Users/xxxxxxxxxx/workspace/insta_clone/vendor/bundle/ruby/2.6.0/gems/msgpack-1.4.2/lib/msgpack.rb:8:in `<top (required)>'
/Users/xxxxxxxxxx/workspace/insta_clone/vendor/bundle/ruby/2.6.0/gems/msgpack-1.4.2/lib/msgpack.rb:8:in `require': incompatible library version - /Users/xxxxxxxxxx/workspace/insta_clone/vendor/bundle/ruby/2.6.0/gems/msgpack-1.4.2/lib/msgpack/msgpack.bundle (LoadError)
Gem-file
source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby '2.6.4'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.2.6'
# Use mysql as the database for Active Record
gem 'mysql2', '>= 0.4.4', '< 0.6.0'
# Use Puma as the app server
gem 'puma', '~> 3.11'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'mini_racer', platforms: :ruby

# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use ActiveStorage variant
# gem 'mini_magick', '~> 4.8'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.1.0', require: false

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end

group :development do
  # Access an interactive console on exception pages or by calling 'console' anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '>= 3.0.5', '< 3.2'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

group :test do
  # Adds support for Capybara system testing and selenium driver
  gem 'capybara', '>= 2.15'
  gem 'selenium-webdriver'
  # Easy installation and use of chromedriver to run system tests with Chrome
  gem 'chromedriver-helper'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

試したこと

以下いくつか確認しました。

・ローカルのrubyが2.6.4と確認。

% rbenv local                        
2.6.4

% rbenv global                       
system

・which rubyとwhich bundleも同じ階層にいることを確認。

% which ruby                         
/Users/xxxxxxxxx/.anyenv/envs/rbenv/shims/ruby

% which bundle                       
/Users/xxxxxxxxx/.anyenv/envs/rbenv/shims/bundle

・他のRailsプロジェクトではrails -vが問題なく作動することを確認
rbenv rehashを実行後再度bundle install --path vendor/bundleを実行したが変化なし
gem update --systemを実行したが変化なし
rubyを一度uninstallして再度install → bundle install --path vendor/bundleを実行したが変化なし

解決できた方法

vendor/bundleディレクトリ以下を全削除してから再度bundle install --path vendor/bundleをしたところエラーがなくなりrails -vやrails sが動作するようになりました!

MySql2のインストール時のエラーについて

% bundle exec rails new . -d mysql --skip-coffee --skip-turbolinks

と実行したらmysqlのインストールでエラーが起こったので解決方法と参考にしたサイトを残しておきます!

以下手順

$ bundle init
$ Gemfile内に以下を記載。

ruby '2.6.4'
gem 'rails', '~> 5.2.6'

$ bundle install --path vendor/bundle
$ bundle exec rails new . -d mysql --skip-coffee —skip-turbolinks
=>エラーが複数出る。

① Gemfileがコンフリクトしているので上書きしていいか聞かれる。
=> yと答え、上書きした。Gemfile内のrubyrailsのバージョンを再度指定のものに変更しておく。

② その次にBundler could not find compatible versions for gem "sprockets":と、依存関係にあるGemのバージョンコンフリクトが出たので指示通りbundle updateをした。

③ すると以下のエラーメッセージが出た。

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

In Gemfile:
  mysql2

=> 記載通りgem install mysql2 -v '0.5.3を実行したら再度エラーになり、そもそも環境にmysqlがない為だったらしくbrew install mysqlを実行したところ以下が表示された。

Building native extensions. This could take a while...
ERROR:  Error installing mysql2:
        ERROR: Failed to build gem native extension.

    current directory: /Users/XXXXXXXXXXX/.anyenv/envs/rbenv/versions/2.6.4/lib/ruby/gems/2.6.0/gems/mysql2-0.5.3/ext/mysql2
/Users/XXXXXXXXXXX/.anyenv/envs/rbenv/versions/2.6.4/bin/ruby -I /Users/XXXXXXXXXXX/.anyenv/envs/rbenv/versions/2.6.4/lib/ruby/2.6.0 -r ./siteconf20211210-62260-1xigybm.rb extconf.rb
checking for rb_absint_size()... yes
checking for rb_absint_singlebit_p()... yes
checking for rb_wait_for_single_fd()... yes
-----
Using mysql_config at /usr/local/bin/mysql_config
-----
checking for mysql.h... yes
checking for errmsg.h... yes
checking for SSL_MODE_DISABLED in mysql.h... yes
checking for SSL_MODE_PREFERRED in mysql.h... yes
checking for SSL_MODE_REQUIRED in mysql.h... yes
checking for SSL_MODE_VERIFY_CA in mysql.h... yes
checking for SSL_MODE_VERIFY_IDENTITY in mysql.h... yes
checking for MYSQL.net.vio in mysql.h... yes
checking for MYSQL.net.pvio in mysql.h... no
checking for MYSQL_ENABLE_CLEARTEXT_PLUGIN in mysql.h... yes
checking for SERVER_QUERY_NO_GOOD_INDEX_USED in mysql.h... yes
checking for SERVER_QUERY_NO_INDEX_USED in mysql.h... yes
checking for SERVER_QUERY_WAS_SLOW in mysql.h... yes
checking for MYSQL_OPTION_MULTI_STATEMENTS_ON in mysql.h... yes
checking for MYSQL_OPTION_MULTI_STATEMENTS_OFF in mysql.h... yes
checking for my_bool in mysql.h... no
-----
Don't know how to set rpath on your system, if MySQL libraries are not in path mysql2 may not load
-----
-----
Setting libpath to /usr/local/Cellar/mysql/8.0.27/lib
-----
creating Makefile

current directory: /Users/XXXXXXXXXXX/.anyenv/envs/rbenv/versions/2.6.4/lib/ruby/gems/2.6.0/gems/mysql2-0.5.3/ext/mysql2
make "DESTDIR=" clean

current directory: /Users/XXXXXXXXXXX/.anyenv/envs/rbenv/versions/2.6.4/lib/ruby/gems/2.6.0/gems/mysql2-0.5.3/ext/mysql2
make "DESTDIR="
compiling client.c
compiling infile.c
compiling mysql2_ext.c
compiling result.c
compiling statement.c
linking shared-object mysql2/mysql2.bundle
ld: library not found for -lssl
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [mysql2.bundle] Error 1

make failed, exit code 2

Gem files will remain installed in /Users/XXXXXXXXXXX/.anyenv/envs/rbenv/versions/2.6.4/lib/ruby/gems/2.6.0/gems/mysql2-0.5.3 for inspection.
Results logged to /Users/XXXXXXXXXXX/.anyenv/envs/rbenv/versions/2.6.4/lib/ruby/gems/2.6.0/extensions/x86_64-darwin-20/2.6.0/mysql2-0.5.3/gem_make.out

=>そこでエラー内容を検索し、以下参考サイトを見つけ
https://qiita.com/fukuda_fu/items/463a39406ce713396403
https://qiita.com/HrsUed/items/ca2e0aee6a2402571cf6
サイトの記載通り

% 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 updateしたら無事に解決できました。

LDFLAGSとかCPPFLAGSやldや-lsslなどについてざっと読んだだけでは理解できず、現段階でどこまで時間をかけて理解しておけばいいのか聞いたところ、特に理解しなくていいとのことでした!!

mysqlインストール時のエラーの備忘録として残しておきます。

git rebaseの注意点とgit rebase -i -p Head~○コマンドについて

Gitについて以下の動画で復習をしました!
https://www.udemy.com/course/unscared_git/learn/lecture/6680208#content

有料でしたがとてもわかりやすく、全体を一気に復習できるのでおすすめです。
Gitがどのようなデータ構造で、裏でどのように動いているのかも含め解説してくれたので、コマンドを覚えたり使い慣れるだけでなく、このコマンド裏で何が起こっているかがわかるようになりGitを扱う際の恐怖心が減りました。

ここで自分が少し難しいなと感じたgit rebaseについて、いくつか注意点を書いていきます。

※rebaseコマンドとは変更を取り込む際に履歴を一直線に綺麗に整えるために使うコマンド
※mergeコマンドと似ているが、mergeは取り込んだ際にマージコミットを新規作成する

rebaseの注意点

* GitHubにプッシュ済のコミットをrebaseするのはNG!

→プッシュ済のコミットをrebase(新しいコミットIDが付与される)すると次プッシュする際にGitHub(リモートリポジトリ)とローカルとの間の履歴が異なるのでプッシュできなくなる。

* git push -fは絶対NG

→強制的(force)にプッシュはGitHubの履歴が壊れてしまうのでダメ

* プッシュしていないローカルの変更にはrebaseを使い、プッシュした後はmergeを使うようにする


* 複数のコミットをやり直すときgit rebase -i Head~○を使うとマージコミットが表示されないので表示する場合git rebase -i -p Head~○と打つ

→マージコミットが存在する場合「-p」を入れないとGitのエディタ上にマージコミットが表示されず、マージコミット抜きでrebaseされてしまうので注意。(マージコミットが履歴から消える)

上記の注意点について説明します。
  1. masterブランチからfeatureブランチを作成しfeature1.htmlファイルを作成しコミット。
#featureブランチ
% git log --oneline  
aa2a0f9 (HEAD -> feature) feature1.htmlを新規作成
78165e5 (origin/master, master) initial commit


2.masterブランチに切り替え、master1.htmlファイルを作成しコミット。
※つまりmasterとfeatureブランチで枝分かれして作業している状態にする。

#masterブランチ
% git log --oneline 
3c7902e (HEAD -> master) master1.htmlを新規作成
78165e5 (origin/master) initial commit


3. masterブランチでfeatureブランチの変更をgit merge featureで取り込むとマージコミット(Merge branch 'feature')が作成される。

#masterブランチ
% git log --oneline
b6c0614 (HEAD -> master) Merge branch 'feature'
3c7902e master1.htmlを新規作成
aa2a0f9 (feature) feature1.htmlを新規作成
78165e5 (origin/master) initial commit


4. masterブランチで
* git rebase -i -p Head~2とした場合 Gitのエディタが立ち上がり以下のように表示される。

pick 3c7902e master1.htmlを新規作成
pick aa2a0f9 feature1.htmlを新規作成
pick b6c0614 Merge branch 'feature'

この場合Merge branch 'feature'というマージコミットも含まれているので、何も変更せずGitのエディタを閉じれば問題なく終了でき、変更履歴(git log)も変わらない。

* git rebase -i Head~2とした場合以下のように表示される。

pick 3c7902e master1.htmlを新規作成
pick aa2a0f9 feature1.htmlを新規作成

この場合Merge branch 'feature'というマージコミットが含まれていないのでGitのエディタを閉じるとマージコミット無しの状態でリベースされてしまう為、以下のように変更履歴(git log)からマージコミットが消えてしまうので注意!!

% git log --oneline   
28bb459 (HEAD -> master) feature1.htmlを新規作成
3c7902e master1.htmlを新規作成
78165e5 (origin/master) initial commit


最初、自分はマージコミットが含まれている状態でGitHubにプッシュした直後にgit rebase -i Head~Xしてしまった為(上記の注意点でNGと記載)、ローカルのマージコミットが消えていたらしく、それに気づかず次の作業後にプッシュしようとした際にリモートとローカルの履歴に差が生じた(ローカルからマージコミットが消失)のでプッシュできないと怒られました。。
このことから、(1)GitHubにプッシュ済のコミットをrebaseするのはNG(2)マージコミットがある場合には基本的にはgit rebase -i -p Head~○とした方が安全ということを学びました!