LoginSignup
30
29

More than 5 years have passed since last update.

Ruby on Rails で sqlite3 から mysql に切り替えたい

Last updated at Posted at 2019-04-07

目的

Ruby on Rails で sqlite3 を使ってるけど、mysql に切り替えたい

やり方

Gemfileの編集

Gemfile に以下を追記する
ついでに sqlite3 は使用しないのでコメントアウトしておく

#gem 'sqlite3', '~> 1.3.6'
gem 'mysql2'

bundle install 実行

[root@localhost work]# bundle install --path=vendor/bundle

なんかエラーが出た

An error occurred while installing mysql2 (0.5.2), and Bundler cannot continue.
Make sure that `gem install mysql2 -v '0.5.2' --source 'https://rubygems.org/'` succeeds ```
before bundling.

エラーの通りのコマンド実行してからinstallしても同じエラーになる

[root@localhost work]# gem install mysql2 -v '0.5.2' --source 'https://rubygems.org/'

こちらのサイトを参照して下記コマンド実行してからで installできました
https://qiita.com/tktcorporation/items/0ef8c930fc18ce72c301

[root@localhost work]# bundle config --local build.mysql2 "--with-cppflags=-I/usr/local/opt/openssl/include"

rails側の設定ファイル変更

sqlite3 の部分をコメントアウトして、mysql用の設定を追記する
database や user などは適宜書き換える

config/database.yml
...
default: &default
#  adapter: sqlite3
#  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
#  timeout: 5000
  adapter: mysql2
  database: table_name
  username: user
  password: password
  host: 127.0.0.1
  encoding: utf8

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

test:
  <<: *default
#  database: db/test.sqlite3

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

...

migrate実行

上で記述したデータベースは作成済みの前提

[root@localhost work]# bundle exec rake db:migrate
== 20190331035940 CreatePosts: migrating ======================================
-- create_table(:posts)
   -> 0.0100s
== 20190331035940 CreatePosts: migrated (0.0100s) =============================

いい感じにマイグレできたっぽいです

アプリケーションを実行して問題ないか確認

[root@localhost work]# rails s -b 0.0.0.0

http://localhost:3000/ にアクセスして表示できればOK
ただレコードの移行などはできていない状態です

最初からこうしておけばよかったのに

rails new コマンド実行時にデータベース指定できるようです

rails new application_name --database=mysql

参考にしたサイト

https://www.oiax.jp/rails3book/setup_mysql.html
https://www.sendai-freelance.com/entry/2017/05/10/232516

30
29
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
30
29