Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Establish a connection to another database only in a block?

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

class LinkCreator
  attr_accessor :animal

  def initialize(animal:)
    @animal = animal
  end

  def call
    "something#{link_id}"
  end

  private

  def link_id
    connection.execute(sql_request).first.first
  end

  def sql_request
    "SELECT field FROM table WHERE field_id = '#{field_id}' LIMIT 1"
  end

  def field_id
    animal.field_id
  end

  def 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
end

As you can see, this is not a model but only a simple class. The problem is than the connection of activerecord is changed and the other requests, later, are executed on the new connection.

Is it possible to establish a connection only in a block and go back to the old connection. I know I can establish another connection but this is very bad for performance.

like image 339
Dougui Avatar asked Dec 20 '25 02:12

Dougui


1 Answers

It would be nice if you keep all database connections in database.yml

development:
  adapter: mysql2
  other stuff...
  
db_2:
  adapter: mysql2
  other stuff..

other_envs:
.....

Then create a class

class OtherDB < ActiveRecord::Base
  establish_connection(:db_2)
end

From your controller you can access just like

OtherDB.table_name = "table_name"
OtherDB.first

Check my blog here http://imnithin.github.io/multiple-database.html

like image 57
Nithin Avatar answered Dec 22 '25 16:12

Nithin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!