Rails Database Connection with Block
Posted on December 4th, 2008
I found myself needing to very quickly connect to an alternate database that was defined in my database.yml like so:
alternate_data:
adapter: mysql
database: alternate_database
username: user
password: pass
host: localhostI was accessing it with something similar to the following:
ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations["#{state}_data"]) results = connection.execute description_params[:extraction_sql]; #This wasn't actually hard coded, but this is just an example ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations["development"])
The problems with this was that I had to repeat this ugly code everywhere, and if there was an exception thrown while accessing the alternate database it would not revert back to the original before exiting. So the next request to the server thought the default database was the alternate database. What I decided would be useful would be to have an “establish_connection” method that accepted a block and handle these issues.







