あかんわ

覚えたことをブログに書くようにすれば多少はやる気が出るかと思ったんです

Mac OSX El CapitanでRuby on RailsからPostgreSQLを使う 後編

開発環境の構築で、Rails4.2.6からPostgreSQLを使うために試行錯誤した記録です。

MacPostgreSQLを入れるまでの作業は、前編に書いています。

目次

railsやrakeのコマンド入力時の注意

今回の環境ではbundle execを省略できる設定をしているため、コマンド入力時はrailsrakeから入力していますが、そのような設定をしていない場合は、bundle exec railsとかbundle exec rakeと入力して下さい。

rails newでデータベースの種類を設定

Railsアプリケーションの作成時に、-dオプションでデータベースをPostgreSQLに設定します。

$ rails new railsapp -d postgresql
  • rails new … アプリケーションを作成
  • railsapp … アプリ名
  • -d postgresql … データベースにPostgreSQLを設定

-dオプションによるデータベースの設定が無い場合は、デフォルトでsqlite3が設定されGemfileのデータベースの項目やdatabase.yml*1sqlite3が設定されるようです。

database.ymlを環境に合わせて編集

database.ymlを編集し、Heoku Dev Centerの記事で推奨していたdevelopmentの設定を有効*2にします。

$vi config/database.yml 
default: &default
  adapter: postgresql
  encoding: unicode
  # for details on connection pooling, see rails configuration guide
  # http://guides.rubyonrails.org/configuring.html#database-pooling
  pool: 5

development:
  <<: *default
  database: railsapp_development

  # the specified database role being used to connect to postgres.
  # to create additional roles in postgres see `$ createuser --help`.
  # when left blank, postgres will use the default role. this is
  # the same name as the operating system user that initialized the database.
  username: railsapp

  # the password associated with the postgres role (username).
  #password:

  # connect on a tcp socket. omitted by default since the client uses a
  # domain socket that doesn't need configuration. windows does not have
  # domain sockets, so uncomment these lines.
  host: localhost

usernamelocalhostの設定が無くてもRailsからPostgreSQLを使える場合があるようですが、思いもよらない事態に遭遇する可能性を減らすために、設定しておいた方が無難なようです。
セキュリティが気になる場合は、passwordを設定*3します。

データベース作成権限のあるユーザを作成

database.ymlusernameに設定したユーザ*4を、データベース作成権限のあるユーザとして作成します。

まずは、PostgreSQLサーバを起動します。

$pg_ctl start
server starting
LOG:  redirecting log output to logging collector process                                                               
HINT:  Future log output will appear in directory "pg_log"

PostgreSQLサーバが起動したら、--createdbオプションを付けてユーザを作成します。

$createuser --createdb railsqpp

ユーザを作成しても何も表示されなくて不安になったので、ちゃんとできているか確認します。

$psql postgres
Expanded display is used automatically.
Null display is "NULL".
psql (9.5.1)
Type "help" for help.

postgres=# SELECT * from pg_user;
 usename  | usesysid | usecreatedb | usesuper | userepl | usebypassrls |  passwd  | valuntil | useconfig 
----------+----------+-------------+----------+---------+--------------+----------+----------+-----------
 b0npu    |       10 | t           | t        | t       | t            | ******** | NULL     | NULL
 railsapp |    16384 | t           | f        | f       | f            | ******** | NULL     | NULL
(2 rows)

usecreatedbt(多分Trueの略)なユーザが、ちゃんと出来てました(*´∀`)

rake db:createでデータベースを作成

準備が出来たので、開発環境用のデータベースとテスト用のデータベースを作成*5します。
psqlSQLの直打ちでも良さそうですが、rakeコマンドの動作確認を兼ねてdb:createを使います。

$rake db:create
  • rake … Rubyで記述されたビルドツール
  • db:create … database.ymlに設定したdbを作成

db:createの後ろにRAILS_ENV=オプションを追加し、developmenttestのみを指定してデータベースを作成する事もできるらしいですが、このオプションが無い場合のデフォルトでは、 developmenttestの両方のデータベースが作成できるようです。

コマンド入力後に特に何も表示されなくて不安になったので、念のためデータベースの一覧を表示してみます。

$psql -l
Expanded display is used automatically.
Null display is "NULL".
                                   List of databases
        Name          | Owner    | Encoding |   Collate   |    Ctype    | Access privileges 
----------------------+----------+----------+-------------+-------------+-------------------
 railsapp_development | railsapp | UTF8     | ja_JP.UTF-8 | ja_JP.UTF-8 | 
 railsapp_test        | b0npu    | UTF8     | ja_JP.UTF-8 | ja_JP.UTF-8 | 
 postgres             | b0npu    | UTF8     | ja_JP.UTF-8 | ja_JP.UTF-8 | 
 template0            | b0npu    | UTF8     | ja_JP.UTF-8 | ja_JP.UTF-8 | =c/b0npu           +
                      |          |          |             |             | b0npu=CTc/b0npu
 template1            | b0npu    | UTF8     | ja_JP.UTF-8 | ja_JP.UTF-8 | =c/b0npu           +
                      |          |          |             |             | b0npu=CTc/b0npu
(4 rows)

オーナーがrailsqpprailsapp_developmentデータベースと、オーナーがb0npu*6railsapp_testデータベースが準備出来ました(*゚∀゚)

rake db:migrateでdb/schema.rbを用意する

db/schema.rbが無いと、テスト駆動開発(TDD)や振舞起動開発(BDD)で、モデルを作成する前のコントローラやビューのテストの時に、db/schema.rb doesn't exist yet. Runrake db:migrateto create it, then try again.とか怒られる場合があるようなので、先に用意しておきます。

$rake db:migrate

rakeコマンドを実行しても、モデルやマイグレーションファイルがありませんので特に何も表示されませんが、db/schema.rbは作成されました。

$more db/schema.rb 
# encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.

ActiveRecord::Schema.define(version: 0) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

end

ついでに、developmentのデータベースにはschema_migrationsテーブルが作成されます。

$psql railsapp_development
Expanded display is used automatically.
Null display is "NULL".
psql (9.5.1)
Type "help" for help.

railsapp_development=# \d
              List of relations
 Schema |       Name        | Type  | Owner  
--------+-------------------+-------+----------
 public | schema_migrations | table | railsapp
(1 row)

これにて、RailsからPostgreSQLを使うための準備完了です(`・ω・´)

参考記事

使い慣れた開発環境で作業するため、最新*7第3版ではなく第2版を参考にしています。 railstutorial.jp

PostgreSQLのインストールについては、こちらの記事を参考にさせていただきました。

開発環境

*1:データベースの設定ファイル

*2:usernameとlocalhostはデフォルトではコメントされていました

*3:デフォルトではコメントアウトされています

*4:PostgreSQLではユーザをロールと言うらしい

*5:当然ですがPostgreSQLサーバが起動していないとエラーが出ます

*6:データベースがインストールされているOSのユーザ

*7:2016年4月時点