Mac OSX El CapitanでRuby on RailsからPostgreSQLを使う 後編
開発環境の構築で、Rails4.2.6からPostgreSQLを使うために試行錯誤した記録です。
MacにPostgreSQLを入れるまでの作業は、前編に書いています。
目次
- 目次
- railsやrakeのコマンド入力時の注意
- rails newでデータベースの種類を設定
- database.ymlを環境に合わせて編集
- データベース作成権限のあるユーザを作成
- rake db:createでデータベースを作成
- rake db:migrateでdb/schema.rbを用意する
- 参考記事
- 開発環境
railsやrakeのコマンド入力時の注意
今回の環境ではbundle exec
を省略できる設定をしているため、コマンド入力時はrails
やrake
から入力していますが、そのような設定をしていない場合は、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
*1にsqlite3
が設定されるようです。
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
username
やlocalhost
の設定が無くてもRailsからPostgreSQLを使える場合があるようですが、思いもよらない事態に遭遇する可能性を減らすために、設定しておいた方が無難なようです。
セキュリティが気になる場合は、password
を設定*3します。
データベース作成権限のあるユーザを作成
database.yml
でusername
に設定したユーザ*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)
usecreatedb
がt
(多分Trueの略)なユーザが、ちゃんと出来てました(*´∀`)
rake db:createでデータベースを作成
準備が出来たので、開発環境用のデータベースとテスト用のデータベースを作成*5します。
psql
でSQLの直打ちでも良さそうですが、rake
コマンドの動作確認を兼ねてdb:create
を使います。
$rake db:create
db:create
の後ろにRAILS_ENV=
オプションを追加し、development
やtest
のみを指定してデータベースを作成する事もできるらしいですが、このオプションが無い場合のデフォルトでは、
development
とtest
の両方のデータベースが作成できるようです。
コマンド入力後に特に何も表示されなくて不安になったので、念のためデータベースの一覧を表示してみます。
$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)
オーナーがrailsqpp
なrailsapp_development
データベースと、オーナーがb0npu
*6なrailsapp_test
データベースが準備出来ました(*゚∀゚)
rake db:migrateでdb/schema.rbを用意する
db/schema.rb
が無いと、テスト駆動開発(TDD)や振舞起動開発(BDD)で、モデルを作成する前のコントローラやビューのテストの時に、db/schema.rb doesn't exist yet. Run
rake 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のインストールについては、こちらの記事を参考にさせていただきました。
開発環境
- OSX 10.11.4 El Capitan
- テキストエディタ: MacVim
- ターミナルエミュレータ: Macターミナル
- シェル: zsh
- パッケージマネージャ: Homebrew - Ruby 2.3.0
- バージョンマネージャ: rbenv
- Webフレームワーク: Ruby on Rails - データベース
- ORDBMS: PostgreSQL