LoginSignup
68
61

More than 5 years have passed since last update.

Rails で postgresql を使う(インストールからマイグレーションまで)

Last updated at Posted at 2018-02-02

はじめに

Rails アプリケーションの開発を進めていくなかで、ついつい sqlite に頼ったままどんどん前に進んでしまうことがよくある。
MySQL か postgreSQL に変えなきゃな〜〜と思いつつ sqlite をそのまま使いつづけるのを防ぐため、まとめておく。

postgresql の設定

Homebrew でインストール

$ brew update
$ brew install postgresql

起動&接続

以下で実行してみる。

$ postgres

エラーになるはず。

postgres does not know where to find the server configuration file.
You must specify the --config-file or -D invocation option or set the PGDATA environment variable.

コンフィグファイルを指定していないのが原因

postgresql を brew で install したときに、
/usr/local/var/postgres
が作成されている。これを環境変数にセットしておく。
~/.bashrc に以下を追加。

export PGDATA='/usr/local/var/postgres'

もちろん $ source ~/.bashrc する。

今度は起動できる

$ postgres

起動した状態で、別プロセスから接続可能

$psql -d postgres
psql (9.6.3)
Type "help" for help.
postgres=#

Rails の設定とか

database.yml

config/database.yml を以下のように変える。

config/database.yml
default: &default
adapter: postgresql
encoding: utf8
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
username: user
password: pass
host: localhost
timeout: 5000

development:
<<: *default
database: hoge_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: hoge_test

production:
<<: *default
database: hoge_production

設定に合わせてDB&user作成

便利な createdb/dropdb などのコマンドがあるのでそれを使う。

$ createdb hoge_production
$ createdb hoge_development
$ createdb hoge_test
$ createuser user

マイグレーション

以下で development 環境の DB をマイグレーション

$rails db:migrate RAILS_ENV=development

以下で確認可能

$ rails db
$ psql -d hoge_development
68
61
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
68
61