Establish a connection to another database only in a block?

It would be nice if you keep all database connections in database.yml

development:
  adapter: mysql2
  other stuff...
  
db_2:
  adapter: mysql2
  other stuff..

other_envs:
.....

Then create a class

class OtherDB < ActiveRecord::Base
  establish_connection(:db_2)
end

From your controller you can access just like

OtherDB.table_name = "table_name"
OtherDB.first

Check my blog here http://imnithin.github.io/multiple-database.html


Have found most short example in Rails codebase at activerecord/test/support/connection_helper.rb and slightly adapted:

def with_another_db(another_db_config)
  original_connection = ActiveRecord::Base.remove_connection
  ActiveRecord::Base.establish_connection(another_db_config)
  yield
ensure
  ActiveRecord::Base.establish_connection(original_connection)
end

Usage (given that you have another_db: section in your database.yml):

with_another_db(ActiveRecord::Base.configurations['another_db']) do
    ActiveRecord::Base.connection.execute("SELECT 'Look ma, I have changed DB!';")
end