0
1

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 3 years have passed since last update.

【Ruby on Rails】PJ立ち上げ時にDBをsqliteからmysqlに変更する方法

Last updated at Posted at 2020-08-25

【Ruby on Rails】PJ立ち上げ時にDBをsqliteからmysqlに変更する方法

rails new PJ名でPJを作成すると、デフォルトのDBはsqlite3になっている。

DBの変更方法は2種類。

  1. PJ立ち上げ時にmysqlを指定する方法
    2. エラー1「active record.nodatabaseerror」の対応
    3. [エラー2「An error occurred while installing mysql2」の対応](#エラー2An-error-occurred-while installing-mysql2」の対応)
  2. 作成後に変更する方法

## 1. PJ立ち上げ時にmysqlを指定する方法

オプションでdatabaseを指定してPJを作成する。

PJの作成
# gemのDBをmysql2に設定する(サーバーにmysql2がインストールされている前提)
$ rails new PJ名 --database=mysql

dbの作成とmigration
## DBの作成
$ rake db:create


## DBを紐付け
$ rake db:migrate

migrateを実行すると、config > dbフォルダの中に、schema.rbが生成される。

image.png

Gemfileで指定されているDBも確認してみる。
DBにmysql2が指定されている。

image.png
Gemfile
gem 'mysql2', '>= 0.3.18', '< 0.6.0'

mysqlとrailsサーバー起動
## mysqlの起動
$ sudo service mysqld start


## railsサーバーの起動
$ rails server -b 0.0.0.0

接続成功。

image.png


### エラー1「active record.nodatabaseerror」の対応 databaseが作成されていない場合に発生するエラー。rakeコマンドでDBの作成と紐付けを行う。
## DBの作成
$ rake db:create


## DBを紐付け
$ rake db:migrate

### エラー2「An error occurred while installing mysql2」の対応 下記エラーが発生した場合、サーバー環境にそもそもmysqlがインストールされていない可能性がある。
エラー
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.

mysql2のインストール

エラー対応
## mysql2(mysql55-devel)のインストール
## インストールするか聞かれるのでyを選択
$ sudo yum install mysql-devel

## Gemfilemとgemライブラリを紐付け
$ bundle install

## dbの作成
$ rake db:create 

## 2. PJ作成後に変更する方法

Gemfileを確認すると、デフォルトのDBはsqlite3が設定されている。

デフォルト
gem 'sqlite3'

1)これを、mysql2に変更する。

Gemfile
gem 'mysql2', '>= 0.3.18', '< 0.6.0'

2)ターミナルで以下を実行

$ bundle install


## db未作成の場合
$ rake db:create 

$ rake db:migrate

mysqlとrailsサーバー起動
## mysqlの起動
$ sudo service mysqld start


## railsサーバーの起動
$ rails server -b 0.0.0.0

既存DBがある場合

既存DBがある場合は、Gemfileを修正し、bundle install後、以下を実行する。

$ rake db:migrate

mysqlとrailsサーバー起動
## mysqlの起動
$ sudo service mysqld start


## railsサーバーの起動
$ rails server -b 0.0.0.0

以上。
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?