70
83

More than 5 years have passed since last update.

Heroku PostgresをRailsアプリで利用する手順

Last updated at Posted at 2017-08-12

もくじ

Heroku Postgres
- URL取得
- 補足:アドオン追加
Rails
- database.yml
- Gemfile
デプロイ
マイグレーション

Heroku Postgres

URL取得

heroku configコマンドでDATABASE_URLを確認する

$ heroku config
=== xxxxx-xxxxx-xxxxx Config Vars
DATABASE_URL:             postgres://<username>:<password>@<host>:<port>/<database>

補足:アドオン追加

DATABASE_URLが表示されない場合、アドオンの追加を行う。

参考:Heroku Postgres | Heroku Dev Center

$ heroku config
=== xxxxx-xxxxx-xxxxx Config Vars

# => DATABASE_URLが表示されない場合は、以下のコマンドを実行してアドオンを追加

$ heroku addons:create heroku-postgresql:hobby-dev

Creating heroku-postgresql:hobby-dev on ⬢ xxxxx-xxxxx-xxxxx... free
Database has been created and is available
 ! This database is empty. If upgrading, you can transfer
 ! data from another database with pg:copy
Created postgresql-xxxxx-xxxxx as DATABASE_URL
Use heroku addons:docs heroku-postgresql to view documentation

$ heroku config
=== xxxxx-xxxxx-xxxxx Config Vars
DATABASE_URL:             postgres://<username>:<password>@<host>:<port>/<database>

# => アドオンが追加され、DATABASE_URLが表示されるようになる

Rails

database.yml

database.ymlで環境変数DATABASE_URLを参照するように設定する

参考:Rails アプリケーションを設定する | Rails ガイド

config/database.yml
production:
  url: <%= ENV['DATABASE_URL'] %>

Gemfile

GemfileでProduction環境でpgを利用するように設定する

Gemfile
# Use sqlite3 as the database for Active Record
gem 'sqlite3', group: [:development, :test]
gem 'pg', group: :production

デプロイ

Herokuにアプリをデプロイする。

参考:HerokuにRailsアプリをデプロイする手順 - Qiita

マイグレーション

デプロイしたアプリでマイグレーションを実施する。

# DBのマイグレーション
$ heroku run rake db:migrate

# dynoの再起動
$ heroku ps:restart

# アプリを開く
$ heroku open
70
83
2

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
70
83