LoginSignup
3
2

More than 3 years have passed since last update.

Ruby on Railsの新しいプロジェクトでSQLite3からPostgreSQLに変更する

Last updated at Posted at 2020-09-02

Ruby on Railsで作った新しいプロジェクトのデータベースを変更する手順のまとめです。

環境

  • mac OS Catalina 10.15.6
  • Ruby 2.6.3
  • Rails 6.0.3.2

SQLiteからPostgreSQL変更する理由

Ruby on Railsのデータベースの標準はSQLite3ですが、HerokuにデプロイするときにSQLite3だとエラーになります。
rails newした時点でPostgreSQLに変更しておくと、あとでデータ移行する手間が省けます。

Postgresを使う準備

macにHomebrewをインストールする

Homebrewのインストールに必要となるxcodeをまずインスロールします。

xcodeをインストールする

xcode-select --install

Homebrewをインストールする

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

公式ページはこちら:Homebrew

macにbrew経由でpostgresをインストールする

postgresqlを指定することで最新の安定版をダウンロードできます。

brew install postgresql

Postgresの初期設定

.bash_profileを更新する

ECHO 'export PGDATA=/usr/local/var/postgres' >> .bash_profile

.bash_profileを再読み込み

source ~/.bash_profile

ユーザーを作成する

データベースを管理するためのユーザーを作ります。

 createuser <username>

RailsプロジェクトでPostgresを使う

GemfileでSQLite3になっている部分をPostgreSQLに変える

Gemfileを更新して、SQLite3の記載をPostgreSQLに変更します。

変更前

Gemfile.rb
# Use sqlite3 as the database for Active Record
gem 'sqlite3', '~> 1.4'

変更後

Gemfile.rb
# Use Postgres as the database for Active Record
gem 'pg'

bundle installでgemをinstallします。

bundle install

database.ymlを編集してデータベースの設定をする

app/config/database.yml
 default: &default
   adapter: postgresql
   encoding: unicode
   pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
   timeout: 5000

 development:
   <<: *default
   database: myapp_dev # 任意のデータベース名

 test:
   <<: *default
   database: myapp_sandbox # 任意のデータベース名

 production:
   <<: *default
   database: myapp_production # 任意のデータベース名
   username: <username> # 任意のユーザー名
   password: request.env['DB_PASSWORD'] # 任意のパスワード
   adapter: postgresql
   encoding: unicode
   pool:  <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

.envにパスワードを書く

database.ymlにそのままパスワードを書いてしまうと、GitHubにPublicで更新したときにパスワードが丸見えになってしまいます。
環境変数を管理するための.envファイルを作りましょう。
.envファイルは.gitignoreに追加してGitHubにアップロードされるのを防ぎましょう。

.env
DB_PASSWORD = '<password>'
.gitignore
.env

データベースをつくる

bundle exec rails db:create

下記のようなメッセージが出ればPostgreSQLでデータベースの作成完了です。

Created database 'myapp_dev'
Created database 'myapp_sandbox'
3
2
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
3
2