5分で構築。MySQLを利用したRailsアプリの雛形を作成するための手順

Ruby

MySQLを利用したRailsアプリを作る機会がたびたびあるので今回手順を作成しました。

サクッと雛形を作りたいときに参考にしてもらえればいいと思います。

なお、MySQL自体はローカルにインストールされている前提で話をします。

ざっくりとした手順
  1. MySQLにユーザーを作成する
  2. Railsアプリを新規作成する
  3. RailsアプリにDBの設定を追加
  4. 起動確認

MySQLの接続確認

まずはMySQLを起動して接続の確認をします。

$ mysql.server start
Starting MySQL
. SUCCESS!

起動後、接続できるか確認します。(mysql_secure_installationでルートのパスワードログインの設定が終わっている前提で話をします。)

$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 747
Server version: 5.7.18 Homebrew

Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

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

mysql>

MySQLにユーザーを作成する

Railsで利用するユーザーを作成します。

今回はrailsuserというユーザーを作成します。パスワードはrailspassとします。

mysql> create user railsuser@'localhost' identified by 'railspass';
Query OK, 0 rows affected (0.00 sec)

以下のコマンドでユーザーが作成されたことが確認できます。

mysql> select User,Host from mysql.user;
+-----------+-----------+
| User      | Host      |
+-----------+-----------+
| mysql.sys | localhost |
| railsuser | localhost |
| root      | localhost |
+-----------+-----------+
3 rows in set (0.00 sec)

権限の付与を行います。

mysql> grant all on *.* to railsuser@'localhost';
Query OK, 0 rows affected (0.00 sec)

なお、ユーザーを削除したいときは以下のようにします。

mysql> drop user railsuser@'localhost';

Railsアプリの作成

まずはディレクトリの作成とbundleの初期化を行います。

$ mkdir hello_rails
$ cd hello_rails
$ bundle init

作成されたGemfileのコメントアウトを戻します。

Gemfile

# frozen_string_literal: true

source "https://rubygems.org"

git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }

- # gem "rails"
+  gem "rails"

bundle installを実行します。

ここでライブラリのインストール先を--pathでアプリ配下に指定することでシステムのgemにインストールされることがなくなります。

その結果、システムのgemにはbundlerのみ、アプリのgemにはアプリで利用するライブラリが格納されることになり、きれいにライブラリの住み分けができるよになります。

$ bundle install --path=vendor/bundle

次にrails newを実行します。bundlerでインストールされたrailsライブラリをbundle execで呼び出して実行します。

rails newをするときにGemfileを上書きするかという質問が聞かれますがここはyesと選択して問題ないです。

rails newbundle exec rails newの違いについては以下の記事を参考にしてください。

$ bundle exec rails new . -d mysql -TB
オプションの説明
  • -dで利用できるデータベースを指定
  • -Tでtest::unitを組み込まないようにする
  • -Bでbundle installをスキップする
rails newをする段階でbundle installが自動で走ります。

Railsアプリを起動する際には`bundle install`をしてアプリケーションに必要なライブラリをインストールする必要がありますが、rails newする段階でbundle installをする必要も特にないのでスキップしてしまうのが一般的です。

(参考)rails newでエラーが起きた場合

以下のようなエラーが起きる場合があります。

An error occurred while installing mysql2 (0.4.5), and Bundler cannot continue.
Make sure that `gem install mysql2 -v '0.4.5'` succeeds before bundling.
         run  bundle exec spring binstub --all
Could not find gem 'mysql2 (< 0.5, >= 0.3.18)' in any of the gem sources listed in your Gemfile.
Run `bundle install` to install missing gems.

この場合、以下のようにすることでmysql2をインストールできます。

$ bundle config --local build.mysql2 "--with-ldflags=-L/usr/local/opt/openssl/lib --with-cppflags=-I/usr/local/opt/openssl/include"
$ bundle install --path=vendor/bundle

正しくインストールされているのがわかります。

$ bundle show | grep mysql2
  * mysql2 (0.4.5)

設定ファイルの変更

新しく作成したRailsアプリケーションの設定ファイルを変更していきます。

ここではDBの設定ファイルのユーザーとパスワードの部分を先ほど作成したものに変更します。

config/database.yml

default: &default
  adapter: mysql2
  encoding: utf8
  pool: 5
  username: railsuser
  password: railspass
  socket: /tmp/mysql.sock

development:
  <<: *default
  database: hello_rails_development

test:
  <<: *default
  database: hello_rails_test

production:
  <<: *default
  database: hello_rails_production
  username: hello_rails
  password: <%= ENV['HELLO_RAILS_DATABASE_PASSWORD'] %>

DBの作成

まずは今回のアプリで利用するDBを作成します。

mysql2のライブラリが必要なのでbundle installします。

$ bundle install
$ bundle exec rails db:create
Created database 'hello_rails_development'
Created database 'hello_rails_test'

DBのマイグレーション

実際にデータベースとテーブルを作成していきます。
今回はサンプルとしてscaffoldでhomeというモデルを作成します。

$ bundle exec rails g scaffold home name:string body:text email:string
$ bundle exec rails db:migrate

データベースの確認

現時点でhello_rails_developmentというデータベースと、その中にhomesというテーブルを作成されたことが確認できます。

$ mysql -u railsuser -prailspass
mysql> use hello_rails_development;
mysql> show tables;
+-----------------------------------+
| Tables_in_hello_rails_development |
+-----------------------------------+
| ar_internal_metadata              |
| entries                           |
| homes                             |
| schema_migrations                 |
+-----------------------------------+
4 rows in set (0.00 sec)

Railsアプリの起動

実際にrailsを起動とデータが正しく作成されるかを確認します。

次にサーバーを起動します。

$ bundle exec rails s

以下のリンクにアクセスすると次のようなページが見れると思います。

この画面からデータを入力することでMySQLにデータが保存されます。

http://localhost:3000/homes

データの確認

先ほどのようにデータベースに接続し、テーブルの中身をみると、実際に画面から作成したデータが入っていることが確認できると思います。

mysql> select * from homes;
+----+--------------+--------------+-------------+---------------------+---------------------+
| id | name         | body         | email       | created_at          | updated_at          |
+----+--------------+--------------+-------------+---------------------+---------------------+
|  1 | ほげほげ       | ふがふが      | mail@address| 2018-02-13 13:52:48 | 2018-02-13 13:52:48 |
+----+--------------+--------------+-------------+---------------------+---------------------+
1 row in set (0.00 sec)