気軽に楽しくプログラムと遊ぶ

自分が興味があってためになるかもって思う情報を提供しています。

PostgresSQLをrailsで使えるようにする

postgresSQLをインストー

$ brew install postgres

起動、停止方法

Macにおいてhomebrewでインストールしたpostgresを停止・起動する方法を以下に示す。

自動起動の場合

# 起動
$ ln -sfv /usr/local/opt/postgresql/*.plist ~/Library/LaunchAgents
$ launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

# 停止
$ launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

手動起動の場合

# 起動
$ pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start

# 停止
$ pg_ctl -D /usr/local/var/postgres stop -s -m fast

設定オプションは
-s エラーメッセージのみを表示
-m mode fast (停止モード:強制終了)

postgresユーザーを作成、postgresユーザーを使って接続確認

$ createuser -P postgres
$ psql -d postgres -U postgres
psql (9.4.5, server 9.4.1)
Type "help" for help.

postgres=>

postgresユーザーにDB作成権限を付与

postgresの権限を確認。権限設定なし。

psql -d postgres -U superuser
psql (9.4.5)
Type "help" for help.

postgres=> \du
                             List of roles
 Role name |                   Attributes                   | Member of
-----------+------------------------------------------------+-----------
 postgres  |                                                | {}
 supseruser| Superuser, Create role, Create DB, Replication | {}

postgresへDB作成権限を追加、再度権限を確認。

postgres=> alter role postgres createdb

                             List of roles
 Role name |                   Attributes                   | Member of
-----------+------------------------------------------------+-----------
 postgres  | Create DB                                      | {}
 supseruser| Superuser, Create role, Create DB, Replication | {}

データベースを作成

pgのgemを追加します。

Gemfile

source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.3'
# Use Postgresql as the database for Active Record
gem 'pg'

・・・

railsのDB設定を作成する。
config/database.ymlにおいてdatabaseの設定を行う

development:
  adapter: postgresql
  host: localhost
  encoding: utf8
  database: db_dev
  pool: 5
  username: postgres
  password: postgres

test:
  adapter: postgresql
  host: localhost
  encoding: utf8
  database: db_test
  pool: 5
  username: postgres
  password: postgres

DBを作成する

$ rake db:create RAILS_ENV=development

作成後の確認

$ psql -l

Ownerがpostgres、Nameが設定したDB名で作成されていることを確認

railsのDB設定が出来ている事を確認する

$ rails dbconsole

参考URL

macOS SierraへのPostgreSQLインストール | 酒と涙とRubyとRailsと [*Rails*] 開発環境用DBをSQLite3からPostgreSQLに変更する - Qiita