Establish a connection to another database only in a block?

后端 未结 7 1133
情书的邮戳
情书的邮戳 2020-12-29 10:17

In a rails application, I have this code in pure ruby :

class LinkCreator
  attr_accessor :animal

  def initialize(animal:)
    @animal = animal
  end

  de         


        
相关标签:
7条回答
  • 2020-12-29 10:54

    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
    
    0 讨论(0)
提交回复
热议问题