10

How to force MySQL reconnect at my will in Rails application? I would like to do this either periodically or on DB exceptions like "MySQL server has gone away".

I found ActiveRecord::Base.remove_connection but as it is written, it should be called for some model, not the whole application.

Paul
  • 25,812
  • 38
  • 124
  • 247

2 Answers2

21

It's a huge pain to restart the Rails console when I'm running it via Heroku with a bunch of objects in variables and then lose my database connection.

The following is code I would not consider "good" to put in your actual application but it temporarily gets over the oft encountered Mysql2::Error: closed MySQL connection in a console:

 ActiveRecord::Base.connection.reconnect!
Aaron
  • 13,349
  • 11
  • 66
  • 105
3

How about using reconnect = true in your database.yml as described here?

Community
  • 1
  • 1
Roope Hakulinen
  • 7,326
  • 4
  • 43
  • 66
  • Doesn't work. I am getting disconnects and then "out of memory" in MySQL2 client. Then WEBrick/Puma stops. – Paul Oct 15 '14 at 21:14