4
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RailsでPostgresqlを使用する

Last updated at Posted at 2019-05-01

rails new したときのデフォルトDBは sqlite だけど、実務で使うことはあまりないと思うのでpostgresqlに変更する。

環境

 $ cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=18.04
DISTRIB_CODENAME=bionic
DISTRIB_DESCRIPTION="Ubuntu 18.04.2 LTS"

Postgresqlのinstall

こちらを参考にinstallする
https://www.postgresql.org/download/linux/ubuntu/

$ sudo emacs /etc/apt/sources.list.d/pgdg.list

# 下記の一文を追加
`deb http://apt.postgresql.org/pub/repos/apt/ bionic-pgdg main`

$ wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
$ sudo apt-get update
$ sudo apt-get install postgresql-10

Postgresqlのアカウントを作成

$ sudo -u postgres psql

# <username>、<password> は任意の値を設定する
postgres=# create role <username> with createdb login password '<password>';

# ロールの確認
postgres=# \du

Postgresqlの接続設定を編集

listen_addresses = '*' に変更

/etc/postgresql/10/main/postgresql.conf
#------------------------------------------------------------------------------
# CONNECTIONS AND AUTHENTICATION
#------------------------------------------------------------------------------

# - Connection Settings -

listen_addresses = '*'		# what IP address(es) to listen on;

Gemfileの編集

gem 'pg'

をGemfileに追記して、bundle install

※ 下記のようなエラーが出て失敗する場合は、

checking for libpq-fe.h... no
Can't find the 'libpq-fe.h header
$ sudo apt-get install libpq-dev

して、bundle install

database.ymlの編集

config/database.yml
default: &default
  adapter: postgresql
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: <username>  # とりあえずベタで
  password: <password>  # とりあえずベタで
  host: localhost  # とりあえず
  timeout: 5000

development:
  <<: *default
  database: <project_name>_development

test:
  <<: *default
  database: <project_name>_test

production:
  <<: *default
  database: <project_name>

DB作成

$ bundle exec rails db:create
Created database '<project_name>_development'
Created database '<project_name>_test'

実際にDBの中も確認する

$ sudo -u postgres psql

postgres=# \l
# <project_name>_development、<project_name>_test、が作成されていることを確認

参考

4
14
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
4
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?