3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Rails】【DB】RailsのDBをMySQL2に変更する方法

Last updated at Posted at 2020-03-25

RailsのDBをMySQL2にする方法を記載します。
まずはdatabase.ymlを記載していきます。

database.yml編集

database.yml
development:
  adapter: mysql2
  encoding: utf8
  database: [アプリケーション名]_development
  pool: 5
  username: [任意のユーザ名]
  password: [任意のパスワード]
  host: localhost

test:
  adapter: mysql2
  encoding: utf8
  database: [アプリケーション名]_test
  pool: 5
  username: [任意のユーザ名]
  password: [任意のパスワード]
  host: localhost

production:
  adapter: mysql2
  encoding: utf8
  database: [アプリケーション名]_production
  pool: 5
  username: [任意のユーザ名]
  password: [任意のパスワード]
  host: localhost

上記のように記載していきます。
[アプリケーション名][任意のユーザ名][任意のパスワード]はご自身のものを記載お願いします。
database.ymlについてはこちらをご参考ください。
続いてMySQL2をインストールしていきます。

MySQL2インストール

Gemfile
gem 'mysql2'
:
:

これでbundle installします。
MySQLではホスト名、ユーザー名、パスワードの指定が必要になるので、設定をしてきます。

ホスト名、ユーザー名、パスワード設定

MySQLにログインします。

$ mysql -u root
:
:
mysql> create user 'ユーザー名'@'localhost' identified by 'パスワード';
mysql> select User,Host from mysql.user;

mysql> create user 'ユーザー名'@'localhost' identified by 'パスワード';ではホスト名、ユーザー名、パスワードを設定しています。
select User,Host from mysql.user;ではユーザーの登録が成功しているか確認を行っています。

続いてユーザーにアカウント権限をつけます。

mysql> grant all on *.* to '[ユーザー名]'@'localhost';

これでMySQL2での設定は完了しました。
先ほどのdatabase.ymlに登録したユーザーホスト名パスワードを記載しましょう。

データベース作成

続いてデータベースを作成して、マイグレーションしていきます。

$ rails db:create
$ rails db:migrate

productionの場合は下記のようにデータベースを作成します。

rails db:create RAILS_ENV=production

これでRailsのDBをMySQL2に変更することができました。

3
3
0

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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?