LoginSignup
0
1

More than 3 years have passed since last update.

SQLite3からPostgreSQLに変更

Posted at

背景

プロジェクトの作成時に

rails new sample_app -d postgresql

とするところを

rails new sample_app -D postgresql

としていたので、ポスグレが設定されていたなかった。

Gemfileで

# Use postgresql as the database for Active Record
gem 'pg'

となっていてほしいところが、

# Use sqlite3 as the database for Active Record
gem 'sqlite3'

となっていた。

sqlite3ってのがデフォルトのやつなのかな。

SQLite3からPostgreSQLに変更

https://qiita.com/rubys8arks/items/0749d6fa73e88d3d381c
これを参考に変更していこう。

ポスグレ自体はインストールされているので、
Gemfileのsqlite3のところを

# Use postgresql as the database for Active Record
gem 'pg', '>= 0.18', '< 2.0'

に変更して、bundle installする。

この状態だと、rails db:createできない

bin/rails db:create
rails aborted!
LoadError: Error loading the 'sqlite3' Active Record adapter. Missing a gem it depends on? sqlite3 is not part of the bundle. Add it to your Gemfile.

database.ymlの編集

before

# SQLite version 3.x
#   gem install sqlite3
#
#   Ensure the SQLite 3 gem is defined in your Gemfile
#   gem 'sqlite3'
#
default: &default
  adapter: sqlite3
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000

development:
  <<: *default
  database: db/development.sqlite3

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  <<: *default
  database: db/test.sqlite3

production:
  <<: *default
  database: db/production.sqlite3

after

default: &default
  adapter: postgresql
  encoding: unicode
  # For details on connection pooling, see Rails configuration guide
  # https://guides.rubyonrails.org/configuring.html#database-pooling
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

development:
  <<: *default
  database: sample_app_development

test:
  <<: *default
  database: sample_app_test

production:
  <<: *default
  database: sample_app_production
  username: sample_app
  password: <%= ENV['SAMPLE_APP_DATABASE_PASSWORD'] %>

.envにパスワード

ここは省略

データベースの作成

-> % bin/rails db:create
Created database 'sample_app_development'
Created database 'sample_app_test'
0
1
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
0
1