【Ruby On Rails 4】DBをPostgresqlに変更する(Ubuntu Server14.04)

sqliteはDBの更新処理時の排他制御がいまいちなので、postgresqlに乗り換える。

必要なパッケージのインストール

$ sudo apt-get install postgresql libpq-dev

Gemfileのsqliteを削除して、postgresを追加

$ vi Gemfile
- gem 'sqlite3'
+ gem "pg"

gemを追加します。

$ bundle install

PostgreSQLサーバの初期設定

PostgreSQL上に、以下2つの管理用ユーザーを作成します。

ここでは、次の2つを使うことにします。

  • gnDwPsFVM5kMU (postgres)
  • diiNv2bid4aTI (hoge)

念のためこれらのパスワードは /root ディレクトリに記録します。

$ sudo -s
% echo "gnDwPsFVM5kMU" > /root/postgres_postgres_password
% echo "diiNv2bid4aTI" > /root/postgres_hoge_password
% chmod 400 /root/postgres_*_password
% exit

adminユーザーとamin_productionデータベースを作ります。

% sudo su - postgres
% createuser -a hoge
% createdb -E UTF8 -O hoge hoge_production -T template0
% psql -c "alter user postgres with password 'gnDwPsFVM5kMU'"
% psql -c "alter user hoge with password 'diiNv2bid4aTI'"
% exit

DB接続時の認証をパスワード認証に変更します。

% sudo vi /etc/postgresql/9.3/main/pg_hba.conf

- local   all             all                                     peer
+ local   all             all                                      md5

設定を反映します。

%  sudo service postgresql reload

DBにhogeユーザーでログインします。 hogeユーザーのパスワードを入力すると、ログインできます。 ログインできれば、postgresqlの設定は完了です。

$ psql -U hoge hoge_production
Password for user hoge:
psql (9.3.12)
Type "help" for help.

hoge_production=#

Railspostgresqlを使う設定

config/database.ymlを以下の通り編集します。

default: &default
adapter: postgresql
username: hoge
password: il9aA35JcBx
encoding: utf8
pool: 5
host: localhost

development:
  <<: *default
  database: hoge_development

test:
  <<: *default
  database: hoge_test

production:
  <<: *default
  database: hoge_production

productionモードでDBを作成します。

$ RAILS_ENV=production rake db:create
$ RAILS_ENV=production rake db:migrate

これで、railsからpostgresqlを利用する設定は完了です。

確認

railsのDBコンソールに接続できれば、正常に設定できています。

$ rails c -e production

以上、Ubuntu14.04でrailsのDBをpostgresqlに変更する手順でした。