Ruby on RailsでPostgresを使う
作成: 2020-08-04
更新: 2020-08-04
SQLite3を使うように作成してしまったRailsプロジェクトで途中からPostgreSQLを使うように変更した際のメモです。
環境は以下です。
- Ubuntu 20.04
- Ruby 2.7.1p83
- Rails 6.0.3.2
- PostgreSQL 12
PostgreSQL12は、localのdocker上で動作しています。
PostgreSQLに変更する
まず、プログラムからPostgreSQLに接続して操作するためのライブラリをインストールします。
Ubuntu 20.04
の場合、libpq-dev
をインストールします。
sudo apt install libpq-dev
続いて、ActiveRecordでPostgreSQLを使えるようにするため、Gemfileを以下のように変更します。
--- a/Gemfile
+++ b/Gemfile
@@ -5,8 +5,8 @@ ruby '2.7.1'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 6.0.3', '>= 6.0.3.2'
-# Use sqlite3 as the database for Active Record
-gem 'sqlite3', '~> 1.4'
+# Use postgres as the database for Active Record
+gem 'pg'
変更後、bundle install
を実行し、gemをインストールします。
bundle install
config/database.yml
をPostgreSQLに接続するように変更します。
--- a/config/database.yml
+++ b/config/database.yml
@@ -5,21 +5,28 @@
# gem 'sqlite3'
#
default: &default
- adapter: sqlite3
+ adapter: postgresql
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
timeout: 5000
+ username: postgres_user
+ password: postgres_user_pass
+ encoding: unicode
development:
<<: *default
- database: db/development.sqlite3
+ database: mydb_development
+ host: localhost
+ port: 15432
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
test:
<<: *default
- database: db/test.sqlite3
+ database: mydb_test
+ host: localhost
+ port: 15432
production:
<<: *default
- database: db/production.sqlite3
+ database: mydb
最後に、以下のコマンドで、データベースを作成できることが確認できれば完了です。
rails db:create