RailsでSQLiteでなくMariadbを利用する

RailsSQLite以外のDBを利用する方法です。今更の内容ですが、備忘録として。Railsのバージョンは「5.0.1」です。

デフォルトではSQLiteを利用する設定になっているので、まずGemfileを更新します。sqlliteの部分をコメントアウトして、MySQL(MariaDB)のライブラリであるmysql2を追加します。

「(プロジェクト名)/Gemfile」
# Use sqlite3 as the database for Active Record
# gem 'sqlite3'

# For MariaDB
gem 'mysql2'

インストールします。

$ bundle install

Railsのデータベース接続定義ファイルである「config/database.yml」をMariaDB接続用に編集します。Rails Guideにサンプルが書いてあるので、そのあたりを参考に。尚、MariaDB側に接続ユーザを事前に作成しておきます。以下の例ではrootですが。。。

Configuring Rails Applications — Ruby on Rails Guides

「config/database.yml」
default: &default
  adapter: mysql2
  encoding: utf8
  host: localhost
  username: root
  password: password
  pool: 5

development:
  <<: *default
  database: maria_development

test:
  <<: *default
  database: maria_test

production:
  <<: *default
  database: maria

rakeコマンドを利用して、データベースを作成します。

$ rake db:create

そのまま適当なモデルを作成し、マイグレーション実行で、MariaDB側にテーブルを作成します。

$ rails generate model User name:string email:string
$ rake db:migrate

実際にMariaDBに接続して確認してみると、dbとテーブルが作成されています。

$ mysql -uroot -p
Enter password:
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 20
Server version: 10.1.21-MariaDB MariaDB Server

Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.

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

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| kessan             |
| maria_development  |
| maria_test         |
| mysql              |
| performance_schema |
+--------------------+
6 rows in set (0.00 sec)

MariaDB [(none)]> use maria_development
Database changed
MariaDB [maria_development]> show tables;
+-----------------------------+
| Tables_in_maria_development |
+-----------------------------+
| ar_internal_metadata        |
| schema_migrations           |
| users                       |
+-----------------------------+
3 rows in set (0.00 sec)

MariaDB [maria_development]> desc users;
+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(11)      | NO   | PRI | NULL    | auto_increment |
| name       | varchar(255) | YES  |     | NULL    |                |
| email      | varchar(255) | YES  |     | NULL    |                |
| created_at | datetime     | NO   |     | NULL    |                |
| updated_at | datetime     | NO   |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)