LoginSignup
5
0

More than 3 years have passed since last update.

【Ruby on Rails】MySQL構築からデータベース変更まで

Last updated at Posted at 2020-10-12

はじめに

様々な記事を参考にしながらなんとか導入できたので、
備忘録として残します。
もしおかしな点や、こうした方がいいなどありましたら
ご教授頂けますと幸いです。

開発環境

ruby 2.5.7
Rails 5.2.4.3
Vagrant 2.2.4
VirtualBox 6.0.14
OS: macOS Catalina
centos 7

流れ

1 vagrant上にMySQLを構築
2 既存アプリをSqliteからMySQLに変更
3 新規アプリをMySQLに設定
※基本的にはvagrant上で行うため、ssh接続しておいてください。

vagrant上にMySQLを構築

CentOS確認

まずは現在のCentOSを確認します。
確認方法はvagrantファイルにあるVagrantfileを確認します。

Vagrantfile
Vagrant.configure("2") do |config|
    GUEST_RUBY_VERSION = '2.5.7'
    config.vm.box = "centos/7"

...

今回はCentOSが7である前提で話を進めます。
CentOSとは仮想環境構築に使用する代表的なLinux系OSです。

MySQLのインストール(CentOS7用)

Vagrant+Rails6+MySQL 開発環境構築
こちらの記事を参考にまずはvagrant上にMySQLを構築します。

ターミナル
$ vagrant ssh
$ sudo yum -y install http://dev.mysql.com/get/mysql-community-release-el7-5.noarch.rpm
$ sudo yum -y install mysql-community-server
$ mysqld --version

バーションが表示されればOKです。

自動起動設定後、MySQL起動

vagrant起動時に自動で起動するように設定します。
2行目はmysqld.service enabledになっていればOKです。

ターミナル
$ sudo systemctl enable mysqld.service
$ sudo systemctl list-unit-files -t service | grep mysqld
$ sudo systemctl start mysqld.service

MySQL初期設定(任意)

https://style.potepan.com/articles/19020.html
こちらの記事がわかりやすかったので、
$ mysql_secure_installation を実行後、
この記事のMySQLの初期設定を実施しよう!から設定してください。

# rootユーザーにパスワードを設定(今回はrootパスワードを設定)
$ /usr/bin/mysqladmin -u root password 'root'

# セキュリティー関連の初期設定(ここでパスワードを聞かれると'root'とする)
$ mysql_secure_installation

設定後、下記を実行しパスワードを入力後、
mysql>
この表示になればOKです。

ターミナル
$ mysql -u root -p

既存アプリをSqliteからMySQLに変更

Railsでmysql2をインストールするときにハマったところ
[初学者]既存アプリのDBをMySQLに変更する方法
上記記事を参考に導入していきます。

railsアプリの作成、データベース確認

試しにscaffoldでpostテーブルを作成します。

ターミナル
$ rails new sam
$ cd sam
$ rails g scaffold post name:string

config/database.ymlがこのような表記になっているかと思います。
初期設定ではsqlite3のデータベースを使用しています。

config/database.yml
default: &default
  adapter: sqlite3
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000

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

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  <<: *default
  database: db/test.sqlite3

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

gemの導入

Gemfile
# Use sqlite3 as the database for Active Record
gem 'sqlite3'

gem 'mysql2'
ターミナル
$ bundle install

エラーが出る場合は下記を実行するか、
Gemfileのgem 'mysql2'のバージョンを
gem 'mysql2', '~> 0.4.4'
に変更してみてください。

ターミナル
$ sudo yum install -y mysql-devel

データベース設定をMySQLに変更

congig/database.yml
default: &default
  adapter: mysql2
  encoding: utf8
  pool: 5
  username: root
  password: 初期設定をした場合はパスワードを記述
  host: localhost

development:
  <<: *default
  database: sam_development # samはアプリ名です。

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  <<: *default
  database: sam_test # samはアプリ名です。

production:
  <<: *default
  database: sample_production
  username: sample_app
  password: <%= ENV['SAMPLE_DATABASE_PASSWORD'] %>

下記でデータベースを作成。

ターミナル
$ bundle exec rake db:create
$ rails db:migrate
ターミナル
$ mysql -u root -p
$ show tables from sam_development;
+---------------------------+
| Tables_in_sam_development |
+---------------------------+
| ar_internal_metadata      |
| posts                     |
| schema_migrations         |
+---------------------------+
3 rows in set (0.00 sec)

このようになっていたら設定完了です。

新規アプリをMySQLに設定

こちらは既存アプリの変更より簡単に出来ます。

ターミナル
$ rails new sample -d mysql
$ cd sample
$ rails g scaffold post name:string
congig/database.yml
default: &default
  adapter: mysql2
  encoding: utf8
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: root
  password: 初期設定をした場合はパスワードを記述
  socket: /var/lib/mysql/mysql.sock

development:
  <<: *default
  database: sample_development

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  <<: *default
  database: sample_test

# As with config/secrets.yml, you never want to store sensitive information,
# like your database password, in your source code. If your source code is
# ever seen by anyone, they now have access to your database.
#
# Instead, provide the password as a unix environment variable when you boot
# the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database
# for a full rundown on how to provide these environment variables in a
# production deployment.
#
# On Heroku and other platform providers, you may have a full connection URL
# available as an environment variable. For example:
#
#   DATABASE_URL="mysql2://myuser:mypass@localhost/somedatabase"
#
# You can use this database configuration with:
#
#   production:
#     url: <%= ENV['DATABASE_URL'] %>
#
production:
  <<: *default
  database: sample_production
  username: sample
  password: <%= ENV['SAMPLE_DATABASE_PASSWORD'] %>
Gemfile
# Use mysql as the database for Active Record
gem 'mysql2', '>= 0.4.4', '< 0.6.0'
ターミナル
$ bundle exec rake db:create
$ rails db:migrate

もしAccess deniedのエラーが出た場合は、
下記のように一度ログイン後、再度上記を実行してください。

ターミナル
$ mysql -u root -p
exit

まとめ

初期設定を行うことによってAccess deniedで弾かれることがありますが、
セキュリティー上仕方がないことかもしれません。
間違っている記述や方法がございましたらご教授頂けますと幸いです。

またtwitterではQiitaにはアップしていない技術や考え方もアップしていますので、
よければフォローして頂けると嬉しいです。
詳しくはこちら https://twitter.com/japwork

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