Rails | Temporary connection to another DB
mouse 1869 · person cloud · link
Last update
2017-07-26
2017
07-26
« — »

All code in the given block will execute on the specified connection:

1
2
3
4
5
6
7
8
9
class MyRecord < ActiveRecord::Base
  def self.with_db(db_config)
    orig_conn = self.remove_connection
    self.establish_connection db_config
    yield if block_given?
  ensure
    self.establish_connection orig_conn || self.configurations[Rails.env]
  end
end

Source: StackOverflow