学習記録

アウトプット用に作りました

RailsでMySQL導入、絵文字対応させる

rails new

rails newして新たなアプリケーションを作成しようとしたら、指定したrailsのgemがないというエラーが出ました。

$ rails _6.1.3.1_ new sample --database=mysql --skip-test
Traceback (most recent call last):
    2: from /Users/SAYO/.rbenv/versions/2.5.1/bin/rails:23:in `<main>'
    1: from /Users/SAYO/.rbenv/versions/2.5.1/lib/ruby/site_ruby/2.5.0/rubygems.rb:300:in `activate_bin_path'
/Users/SAYO/.rbenv/versions/2.5.1/lib/ruby/site_ruby/2.5.0/rubygems.rb:281:in `find_spec_for_exe': can't find gem railties (= 6.1.3.1) with executable rails (Gem::GemNotFoundException)

このエラーを解決するために、railsのgemをインストールしました。

$ gem install rails -v 6.1.3.1
Fetching activesupport-6.1.3.1.gem
Fetching actionview-6.1.3.1.gem
Fetching actionpack-6.1.3.1.gem
Fetching railties-6.1.3.1.gem
Fetching activerecord-6.1.3.1.gem
Fetching activemodel-6.1.3.1.gem
Fetching activejob-6.1.3.1.gem
Fetching activestorage-6.1.3.1.gem
Fetching rails-6.1.3.1.gem
Fetching actiontext-6.1.3.1.gem
Fetching actionmailer-6.1.3.1.gem
Fetching actionmailbox-6.1.3.1.gem
Fetching actioncable-6.1.3.1.gem
Successfully installed activesupport-6.1.3.1
Successfully installed actionview-6.1.3.1
Successfully installed actionpack-6.1.3.1
Successfully installed railties-6.1.3.1
Successfully installed activemodel-6.1.3.1
Successfully installed activerecord-6.1.3.1
Successfully installed activejob-6.1.3.1
Successfully installed activestorage-6.1.3.1
Successfully installed actiontext-6.1.3.1
Successfully installed actionmailer-6.1.3.1
Successfully installed actionmailbox-6.1.3.1
Successfully installed actioncable-6.1.3.1
Successfully installed rails-6.1.3.1
Parsing documentation for activesupport-6.1.3.1
Installing ri documentation for activesupport-6.1.3.1
Parsing documentation for actionview-6.1.3.1
Installing ri documentation for actionview-6.1.3.1
Parsing documentation for actionpack-6.1.3.1
Installing ri documentation for actionpack-6.1.3.1
Parsing documentation for railties-6.1.3.1
Installing ri documentation for railties-6.1.3.1
Parsing documentation for activemodel-6.1.3.1
Installing ri documentation for activemodel-6.1.3.1
Parsing documentation for activerecord-6.1.3.1
Installing ri documentation for activerecord-6.1.3.1
Parsing documentation for activejob-6.1.3.1
Installing ri documentation for activejob-6.1.3.1
Parsing documentation for activestorage-6.1.3.1
Installing ri documentation for activestorage-6.1.3.1
Parsing documentation for actiontext-6.1.3.1
Installing ri documentation for actiontext-6.1.3.1
Parsing documentation for actionmailer-6.1.3.1
Installing ri documentation for actionmailer-6.1.3.1
Parsing documentation for actionmailbox-6.1.3.1
Installing ri documentation for actionmailbox-6.1.3.1
Parsing documentation for actioncable-6.1.3.1
Installing ri documentation for actioncable-6.1.3.1
Parsing documentation for rails-6.1.3.1
Installing ri documentation for rails-6.1.3.1
Done installing documentation for activesupport, actionview, actionpack, railties, activemodel, activerecord, activejob, activestorage, actiontext, actionmailer, actionmailbox, actioncable, rails after 28 seconds
13 gems installed

そしてもう一度rails newします。データベースにMySQLを指定します。

$ rails _6.1.3.1_ new sample --database=mysql --skip-test
$ cd sample/
$ bundle install
Fetching gem metadata from https://rubygems.org/............
Resolving dependencies....
Using rake 13.0.3
Using concurrent-ruby 1.1.8
Using minitest 5.14.4
Using racc 1.5.2
Using crass 1.0.6
Using rack 2.2.3
Using nio4r 2.5.7
Using websocket-extensions 0.1.5
Using marcel 1.0.1
Using mini_mime 1.0.3
Using bindex 0.8.1
Using msgpack 1.4.2
Using bundler 2.2.16
Using byebug 11.1.3
Using ffi 1.15.0
Using rb-fsevent 0.11.0
Using method_source 1.0.0
Using zeitwerk 2.4.2
Using thor 1.1.0
Using tilt 2.0.10
Using semantic_range 3.0.0
Using spring 2.1.1
Using turbolinks-source 5.2.0
Using i18n 1.8.10
Using tzinfo 2.0.4
Using nokogiri 1.11.4 (x86_64-darwin)
Using rack-test 1.1.0
Using rack-mini-profiler 2.3.2
Using rack-proxy 0.6.5
Using sprockets 4.0.2
Using websocket-driver 0.7.3
Using puma 5.3.1
Using mail 2.7.1
Using bootsnap 1.7.5
Using rb-inotify 0.10.1
Using sassc 2.4.0
Using turbolinks 5.2.1
Using activesupport 6.1.3.2
Using loofah 2.9.1
Using listen 3.5.1
Using rails-dom-testing 2.0.3
Using globalid 0.4.2
Using activemodel 6.1.3.2
Using jbuilder 2.11.2
Using rails-html-sanitizer 1.3.0
Using activejob 6.1.3.2
Using activerecord 6.1.3.2
Fetching mysql2 0.5.3
Using builder 3.2.4
Using erubi 1.10.0
Using actionview 6.1.3.2
Using actionpack 6.1.3.2
Using actioncable 6.1.3.2
Using activestorage 6.1.3.2
Using sprockets-rails 3.2.2
Using actionmailer 6.1.3.2
Using railties 6.1.3.2
Using actionmailbox 6.1.3.2
Using sassc-rails 2.1.2
Using webpacker 5.4.0
Using sass-rails 6.0.0
Using web-console 4.1.0
Using actiontext 6.1.3.2
Using rails 6.1.3.2
Installing mysql2 0.5.3 with native extensions
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    current directory: /Users/SAYO/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/mysql2-0.5.3/ext/mysql2
/Users/SAYO/.rbenv/versions/2.5.1/bin/ruby -I /Users/SAYO/.rbenv/versions/2.5.1/lib/ruby/site_ruby/2.5.0 -r ./siteconf20210519-27070-xoi5mn.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/opt/mysql@5.7/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... yes
-----
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/opt/mysql@5.7/lib
-----
creating Makefile

current directory: /Users/SAYO/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/mysql2-0.5.3/ext/mysql2
make DESTDIR\= clean

current directory: /Users/SAYO/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.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/SAYO/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/mysql2-0.5.3 for inspection.
Results logged to /Users/SAYO/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/extensions/x86_64-darwin-20/2.5.0/mysql2-0.5.3/gem_make.out

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

bundle installを実行したらエラーが発生しました。なので下記のコマンドを実行しました。

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

このコマンドでMySQLのgemをインストールすることができました。

参考 : bundle installでmysql2がエラーになる件 - Qiita

config/database.ymlを確認すると以下のようになっています。

default: &default
  adapter: mysql2
  encoding: utf8mb4
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: root
  password:
  host: localhost

development:
  <<: *default
  database: sample_development

test:
  <<: *default
  database: sample_test

production:
  <<: *default
  database: sample_production
  username: sample
  password: <%= ENV['SAMPLE_DATABASE_PASSWORD'] %>

上記のdatabase.ymlにパスワード等を入れれば使えるようになりますが、パスワードをGitHubで管理するのはとても危険なので、環境変数として管理します。そのためにGemfileにdotenvを導入してbundle installします。

gem 'dotenv-rails'

そしてアプリケーションのルートディレクトリに.envファイルを追加します。

$ touch .env

この作成した.envファイルに以下のように記述することでRailsアプリからMySQLと接続可能になります。

DATABASE_DEV_PASSWORD=設定したパスワード

この時に、.gitignoreに下記のように.envを追加しておかないとプッシュした時にパスワード等が結局晒されることになるので注意が必要です。

/.env

DBを生成する前に絵文字をDBに保存することができるに設定しておきます。config/database.ymlファイルを下記のように編集します。

default: &default
  adapter: mysql2
  encoding: utf8mb4
  charset: utf8mb4
  collation: utf8mb4_unicode_ci
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: root
  password: <%= ENV['DATABASE_DEV_PASSWORD'] %>
  host: localhost

そしてここまでの設定を行ったらDBを生成していきます。

$ bundle exec rails db:create
Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
Couldn't create 'sample_development' database. Please check your configuration.
rails aborted!
ActiveRecord::ConnectionNotEstablished: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
/Users/SAYO/workspace/portfolio/sample/sample/bin/rails:5:in `<top (required)>'
/Users/SAYO/workspace/portfolio/sample/sample/bin/spring:10:in `require'
/Users/SAYO/workspace/portfolio/sample/sample/bin/spring:10:in `block in <top (required)>'
/Users/SAYO/workspace/portfolio/sample/sample/bin/spring:7:in `tap'
/Users/SAYO/workspace/portfolio/sample/sample/bin/spring:7:in `<top (required)>'

Caused by:
Mysql2::Error::ConnectionError: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
/Users/SAYO/workspace/portfolio/sample/sample/bin/rails:5:in `<top (required)>'
/Users/SAYO/workspace/portfolio/sample/sample/bin/spring:10:in `require'
/Users/SAYO/workspace/portfolio/sample/sample/bin/spring:10:in `block in <top (required)>'
/Users/SAYO/workspace/portfolio/sample/sample/bin/spring:7:in `tap'
/Users/SAYO/workspace/portfolio/sample/sample/bin/spring:7:in `<top (required)>'
Tasks: TOP => db:create
(See full trace by running task with --trace)

エラーが発生してしまいました。ActiveRecord::ConnectionNotEstablished: Can't connect to local MySQL server through socket '/tmp/mysql.sock'

MySQLにログインしたらエラー解消するかなと思ったので、ログインしました。

$  brew services start mysql@5.7
==> Successfully started `mysql@5.7` (label: homebrew.mxcl.mysql@5.7)

MySQLにログインしてからDBを生成してみました。

$ bundle exec rails db:create
Created database 'sample_development'
Created database 'sample_test'

無事DBを作成することができたので、DBを起動させてみました。

$ rails db
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 5.7.34 Homebrew

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 

DBの文字コードを表示させます。

mysql> show variables like '%char%';
+--------------------------+----------------------------------------------------------+
| Variable_name            | Value                                                    |
+--------------------------+----------------------------------------------------------+
| character_set_client     | utf8mb4                                                  |
| character_set_connection | utf8mb4                                                  |
| character_set_database   | utf8mb4                                                  |
| character_set_filesystem | binary                                                   |
| character_set_results    | utf8mb4                                                  |
| character_set_server     | utf8                                                     |
| character_set_system     | utf8                                                     |
| character_sets_dir       | /usr/local/Cellar/mysql@5.7/5.7.34/share/mysql/charsets/ |
+--------------------------+----------------------------------------------------------+
8 rows in set (0.05 sec)

rails sでサーバーを起動すると、このようなエラーが発生。

Webpacker configuration file not found /Users/SAYO/workspace/portfolio/sample/sample/config/webpacker.yml. 
Please run rails webpacker:install Error: No such file or directory @ realpath_rec - /Users/SAYO/workspace/portfolio/sample/sample/config/webpacker.yml (RuntimeError)

言われた通りにrails webpacker:installをしました。これでwebpackerをインストールすることができました。これでrails sのコマンドを打つとlocalhost:3000起動しました。

絵文字が対応するか確認するためにscafoldを使って簡単な投稿機能を作ってみます。

$ rails g scaffold post title:string body:text
Running via Spring preloader in process 31797
      invoke  active_record
      create    db/migrate/20210519133059_create_posts.rb
      create    app/models/post.rb
      invoke  resource_route
       route    resources :posts
      invoke  scaffold_controller
      create    app/controllers/posts_controller.rb
      invoke    erb
      create      app/views/posts
      create      app/views/posts/index.html.erb
      create      app/views/posts/edit.html.erb
      create      app/views/posts/show.html.erb
      create      app/views/posts/new.html.erb
      create      app/views/posts/_form.html.erb
      invoke    resource_route
      invoke    helper
      create      app/helpers/posts_helper.rb
      invoke    jbuilder
      create      app/views/posts/index.json.jbuilder
      create      app/views/posts/show.json.jbuilder
      create      app/views/posts/_post.json.jbuilder
      invoke  assets
      invoke    scss
      create      app/assets/stylesheets/posts.scss
      invoke  scss
      create    app/assets/stylesheets/scaffolds.scss

投稿管理するテーブルをデータベースに作成します。

$ rails db:migrate
== 20210519133059 CreatePosts: migrating ======================================
-- create_table(:posts)
   -> 0.0791s
== 20210519133059 CreatePosts: migrated (0.0792s) =============================

そして一度サーバーを起動し直します。そしてlocalhost:3000/postsにアクセスすると投稿ページが作成されました。

TitleとBodyに絵文字をつけてフォームで送ることができました。MySQLではどのように保存されているのか確認してみます。$ rails dbMySQLを開いてpostsテーブルの情報を表示させました。

mysql> select * from posts;
+----+---------------+------+----------------------------+----------------------------+
| id | title         | body | created_at                 | updated_at                 |
+----+---------------+------+----------------------------+----------------------------+
|  1 | 🧚‍♀️           | 🐒     | 2021-05-19 13:37:23.225939 | 2021-05-19 13:37:23.225939 |
+----+---------------+------+----------------------------+----------------------------+
1 row in set (0.00 sec)

これで絵文字対応はできたみたいです。