Rails で PG::ObjectInUse: ERROR: database ... is being accessed by other users が出るとき

具体的なエラーメッセージ

Caused by:
PG::ObjectInUse: ERROR:  database "foobar_staging" is being accessed by other users (PG::ObjectInUse)
DETAIL:  There is 1 other session using the database.

対処法の一つ

一度ほかのデータベースに接続してから db:reset なりを実行する。

具体例

$ bundle exec rails console
Loading production environment (Rails 8.0.3)
foobar(prod)* ActiveRecord::Base.establish_connection(
foobar(prod)*   adapter: 'postgresql',
foobar(prod)*   database: 'postgres'
foobar(prod)> )
=> #<ActiveRecord::ConnectionAdapters::ConnectionPool env_name="production" role=:writing>

foobar(prod)> exit

$ bundle exec rails db:migrate:reset
(正常に動作する)

補足

DB用のソフト(DBeaver など)を閉じるというのも有効になる。

Powered by はてなブログ