5
3

More than 5 years have passed since last update.

Rails6 のちょい足しな新機能を試す63(db:system:change 編)

Posted at

はじめに

Rails 6 に追加されそうな新機能を試す第63段。 今回は、 db:system:change 編です。
Rails 6 では、 rails db:system:change で使用するデータベースを変更できるようになりました。

config/database.yml と Gemfile を書き変えます。

Ruby 2.6.3, Rails 6.0.0.rc1 で確認しました。Rails 6.0.0.rc1 は gem install rails --prerelease でインストールできます。

$ rails --version
Rails 6.0.0.rc1

今回は、 PostgreSQL から MySQL に DB を変更してみます。

プロジェクトを作る

PostgreSQL を使うように --database オプションを指定します。

rails new rails6_0_0rc1 --database=postgresql
cd rails6_0_0rc1

マイグレーションを作る

users テーブルを作ります。

$ bin/rails g migration CreateUser name

マイグレーションを実行する

実行前に必要なら、 config/database.yml を編集して、データベース (PostgreSQL) にアクセスできるようにします。

$ bin/rails db:create db:migrate

マイグレーションが普通にできました。

データベースを変更する

ここからが本番です。
データベースを MySQL に変更します。

$ bin/rails db:system:change --to=mysql
    conflict  config/database.yml
Overwrite /app/config/database.yml? (enter "h" for help) [Ynaqdhm]

確認のため、 h を入力してみます。

Overwrite /app/config/database.yml? (enter "h" for help) [Ynaqdhm] h
        Y - yes, overwrite
        n - no, do not overwrite
        a - all, overwrite this and all others
        q - quit, abort
        d - diff, show the differences between the old and the new
        h - help, show this help
        m - merge, run merge tool
Overwrite /app/config/database.yml? (enter "h" for help) [Ynaqdhm]

rails app:update コマンドと似ていますね。
今回は、 Y を入力します。

Overwrite /app/config/database.yml? (enter "h" for help) [Ynaqdhm] Y
       force  config/database.yml
       gsub  Gemfile
       gsub  Gemfile

Gemfile は無条件で書き変えるみたいです。

$ git diff Gemfile
...
-gem 'pg', '>= 0.18', '< 2.0'
+gem 'mysql2', '>= 0.4.4'
...

bundle install を実行する

bundle install を実行して mysql2 gem をインストールします。

$ bundle install

マイグレーションを実行してみる

必要なら config/database.yml を編集して、接続先の情報を書き換えてください。

$ bin/rails db:create db:migrate

何の問題もなく終了しました。
mysql コマンドでも確認できました。

mysql> show create table users\G
*************************** 1. row ***************************
       Table: users
Create Table: CREATE TABLE `users` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

試したソース

試したソースは以下にあります。
https://github.com/suketa/rails6_0_0rc1/tree/try063_db_system_change (rails db:system:change 実行前)
https://github.com/suketa/rails6_0_0rc1/tree/try063_db_system_change_to_mysql (rails db:system:change 実行後)

参考情報

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