Paul
Paul

Reputation: 26650

Force to reconnect MySQL in Rails

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.

Upvotes: 11

Views: 8014

Answers (2)

Aaron
Aaron

Reputation: 14029

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!

Upvotes: 24

Roope Hakulinen
Roope Hakulinen

Reputation: 7405

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

Upvotes: 3

Related Questions