LoginSignup
3
3

More than 1 year has passed since last update.

PostgreSQLを利用すると、rails db:createでエラーが発生するトラブルシューティング

Last updated at Posted at 2020-04-02

環境

Vagrant + Ubuntu 16.04.5 LTS
Rails 5.2.4.2
PostgreSQL9.5.19

はじめに

データベースにPostgreSQLを指定して、データベースを作成しようとすると、PostgreSQLに、vagrantというロールがありませんというエラーが表示されて、Railsからデータベースが作成できません。

$rails new test_migrate -d postgresql
$cd test_migrate
$rails db:create

FATAL:  role "vagrant" does not exist
Couldn't create 'test_migrate_test' database. Please check your configuration.
rails aborted!
ActiveRecord::NoDatabaseError: FATAL:  role "vagrant" does not exist
bin/rails:4:in `<main>'

Caused by:
PG::ConnectionBad: FATAL:  role "vagrant" does not exist
bin/rails:4:in `<main>'
Tasks: TOP => db:create
(See full trace by running task with --trace)

解決方法

PostgreSQLをインストールした時に、postgresというユーザーが作成されているため、postgresユーザーでログインする。

$sudo su - postgres

createuserコマンドは、PostgreSQLのロール(ユーザーという言い方をしてもいいかも知れない)を作成するコマンドです。普段、Ubuntuにログインしているユーザー名のロールを作成します。自分はVagrantを使っているため、vagrantユーザーでログインしているため、vagrant名のロールを作成することになります。また、予め、パスワードを設定しておかないと、pgAdminから接続ができない事るので注意。オプションの-sは、スーパーユーザーの事。

createuserのコマンド解説

~$createuser vagrant -s

\duで、ロールの一覧を表示して、vagrantが追加されている事を確認する。既に存在しているpostgresは、デフォルトで用意されているものです。

~$psql
postgres=#\du

image.png

PostgreSQLからログアウトします。その後、exitをして、postgreユーザーからもログアウトします。

postgres=#\q
~$exit

その後、rails db:createをすれば、問題は解決!

3
3
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
3