Ruby on RailsのDBをMySQLに変えてみた


こんにちは!モリタケンタロウです!
今回はRuby on RailsのDBをデフォルトのSQLiteからMySQLに変更する方法について紹介します。

最初からMySQLのDBを使うと決めてアプリを作る場合は、↓の記事を参考にしてみてください。

とにかくやってみよう!

やることは二つです。

  • データベースの定義ファイル(config/database.yml)を書き換える
  • MySQLをインストールする

ということで、早速config/database.ymlを編集します。

# 編集前
default: &default
  adapter: sqlite3
  pool: 5
  timeout: 5000

development:
  <<: *default
  database: db/development.sqlite3

# 編集後
default: &default
  adapter: mysql2
  encoding: utf8
  pool: 5
  username: root
  password:
  host: localhost

development:
  <<: *default
  database: development

そして、MySQLをインストールするために、GemFileを編集します。

# 編集前
# Use sqlite3 as the database for Active Record
gem 'sqlite3'

# 編集後
# Use mysql2 as the database for Active Record
gem 'mysql2'

そしたら、bundle installでMySQLをインストールします。
何かエラーが出てきたらコチラの記事を参考にしてみてください。

$ bundle install
The dependency tzinfo-data (>= 0) will be unused by any of the platforms Bundler is installing for. Bundler is installing for ruby but the dependency is only for x86-mingw32, x86-mswin32, x64-mingw32, java. To add those platforms to the bundle, run `bundle lock --add-platform x86-mingw32 x86-mswin32 x64-mingw32 java`.
Fetching gem metadata from https://rubygems.org/............

# 省略

Bundle complete! 15 Gemfile dependencies, 62 gems now installed.
Use `bundle info [gemname]` to see where a bundled gem is installed.

うまくインストールできました。
それではアプリを起動して…ってのはもう少し我慢で、その前にMySQLのサービスを起動しないといけないみたいです。
じゃないと、「Mysql2::Error Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)」って怒られて一瞬ショックな気持ちになります。
ということで、sudo service mysqld startコマンドでMySQLのサービスを起動します。
※ これもsudo付けないと「Permission denied」って怒られた…

$ sudo service mysqld start                                         
Initializing MySQL database:  Installing MySQL system tables...

# 省略

Please report any problems at http://bugs.mysql.com/

                                                           [  OK  ]
Starting mysqld:                                           [  OK  ]

サービスを起動したら、今度はDBを作ります。
DB作らないでアプリを起動しても「ActiveRecord::NoDatabaseError Unknown database 'development'」って怒られるだけです。
rails db:createコマンドでconfig/database.ymlに書いてある内容でDBが作られます。

$ rails db:create
Created database 'development'

そしていよいよアプリを起動します。

$ rails server                                                                                                                                                         
=> Booting Puma
=> Rails 5.0.7.2 application starting in development on http://localhost:8080
=> Run `rails server -h` for more startup options
Puma starting in single mode...
* Version 3.12.4 (ruby 2.6.3-p62), codename: Llamas in Pajamas
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://localhost:8080
Use Ctrl-C to stop


できたっぽいですね!
それでは~