user3403959 user3403959 - 2 years ago 66
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 =, username)
@port ='', 3306, 3309)

adapter: 'mysql2',
host: '',
username: username,
password: password,
database: remote_db_name,
port: @port

Then, in a controller I can successfully call for example
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
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 }

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: '',
  username: username,
  password: password,
  database: remote_db_name,
  port: @port

# when you need your local database again:
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download