Quotidien Shaarli

Tous les liens d'un jour sur une page.

January 23, 2022

rails console : ActiveRecord:ConnectionNotEstablished

I restart local database (postgres in a docker container) and then my server bundle exec bin/rails s

After that I go to the console with bundle exec bin/rails c (or bin/rails c or bundle exec rails c),
being in the project root folder.

Sometimes (not sure exactly why yet), environment get messed up.
When trying a request such as : User.count I get a weird error.

could not connect to server: No such file or directory (ActiveRecord::ConnectionNotEstablished)
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

While the server is running locally and could connect to the database.

It happens the console explicitly starts with the following announcement :

Running via Spring preloader in process 1720240

Hey ! That's a good hint.
Of course, I did disregard it completly for a couple hours -- more than once.

The solution is so often related though. You reload the database and the server,
under spring preloader's feet.

spring prelaoder is so lost ! Let's restart it too.

Solution :

spring stop
bin/rails console

and voilà ! It works again.

Edit 2022-01-23 :

Beware, in the new console, if you do User and get this answer :

User (call 'User.connection' to establish a connection)

Solution is very simple : User.last and there you go. Connexion established, problem solved