Railsアプリケーションを開発している際、PostgreSQLデータベースへの接続でつまずくことがあります。この記事では、そのような時に役立つ解決策を共有します。
前提
RailsアプリケーションからPostgreSQLデータベースへの接続時に次のようなエラーが発生しました。
ActiveRecord::ConnectionNotEstablished (could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/tmp/.s.PGSQL.5432"?):
このエラーは、RailsがPostgreSQLサーバーへの接続を試みるも、指定されたUnixドメインソケットが見つからないために発生します。
解決策
1. PostgreSQLサーバーの状態確認
まず、PostgreSQLサーバーが実際に稼働しているかを確認します。ターミナルで次のコマンドを実行してください。
sudo systemctl status postgresql
または、PostgreSQLのインストール方法に応じて、適切なコマンドを使用します。
2. ソケットファイルの場所の確認
PostgreSQLサーバーが稼働していることを確認したら、次にソケットファイルの場所を確認します。デフォルトの場所は通常/var/run/postgresql
ですが、エラーメッセージでは/tmp
を参照しています。
3. Railsのデータベース設定の修正
config/database.yml
内の設定を、実際のPostgreSQLのソケットファイルの場所に合わせて修正します。例えば、デフォルトのソケットファイルの場所を使用している場合は以下のようになります。
default: &default
adapter: postgresql
encoding: unicode
# その他の設定...
development:
<<: *default
database: myapp_development
username: myapp
password: <%= ENV['MYAPP_DATABASE_PASSWORD'] %>
host: /var/run/postgresql
これで、Railsアプリケーションは正しい場所でPostgreSQLサーバーに接続しようとするはずです。