Establish a connection to another database only in a block?

后端 未结 7 1134
情书的邮戳
情书的邮戳 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:48

    It might help to use an instance variable to store the connection. Something like this:

    def connection
      @connection ||= ActiveRecord::Base.establish_connection(
        adapter:  "mysql",
        host:     ENV["MYSQL_HOST"],
        username: ENV["MYSQL_USERNAME"],
        password: ENV["MYSQL_PASSWORD"],
        database: ENV["MYSQL_DB_NAME"]
      ).connection
    end
    

    That way the existing connection is retrieved on future connection attempts, rather than establishing a new one.

提交回复
热议问题