user3403959 user3403959 - 1 year ago 63
Ruby Question

Ruby on Rails - Connect back to app database after SSH Tunnel query

I'm connecting to a remote database through an SSH Tunnel inside an Activerecord::Base called Item.

I have:

require 'net/ssh/gateway'
require 'active_record'
require 'mysql2'

class Item < ActiveRecord::Base
self.table_name = "[table_name]"
@gateway = Net::SSH::Gateway.new(host, username)
@port = @gateway.open('127.0.0.1', 3306, 3309)

ActiveRecord::Base.establish_connection(
adapter: 'mysql2',
host: '127.0.0.1',
username: username,
password: password,
database: remote_db_name,
port: @port
)


Then, in a controller I can successfully call for example
Item.all
and retrieve all the items from that remote table. The problem is that then I go to another view of the app (I'm using devise for the users) and I get this error:

Mysql2::Error: Table '[remote_database_name].users' doesn't exist: SELECT `users`.* FROM `users` WHERE `users`.`id` = 2 ORDER BY `users`.`id` ASC LIMIT 1


How do I connect back to the local database? I tried using
@gateway.shutdown!
and
@gateway.close(@port)
with methods from the controller, but it doesn't work.

Answer Source

Do not use ActiveRecord::Base.establish_connection, call establish_connection on Item class instead:

class Item < ActiveRecord::Base
  establish_connection { # your connection options here }
end

Or, if you have no other choice, then store local database connection options somewhere before calling ActiveRecord::Base.establish_connection and then connect local database manually using stored configuration:

@local_db = Rails.configuration.database_configuration[Rails.env]
@remote_db = {
  adapter: 'mysql2',
  host: '127.0.0.1',
  username: username,
  password: password,
  database: remote_db_name,
  port: @port
}
ActiveRecord::Base.establish_connection(@remote_db)

# when you need your local database again:
ActiveRecord::Base.establish_connection(@local_db)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download