只在一个块中建立到另一个数据库的连接? [英] Establish a connection to another database only in a block?
问题描述
在 Rails 应用程序中,我有这个纯 ruby 代码:
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
如您所见,这不是一个模型,而只是一个简单的类.问题是 activerecord 的连接发生了变化,其他请求稍后在新连接上执行.
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.
推荐答案
如果您将所有数据库连接都保存在 database.yml
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:
.....
然后创建一个类
class OtherDB < ActiveRecord::Base
establish_connection(:db_2)
end
从你的控制器你可以像访问一样
From your controller you can access just like
OtherDB.table_name = "table_name"
OtherDB.first
在这里查看我的博客 http://imnithin.github.io/multiple-database.html
这篇关于只在一个块中建立到另一个数据库的连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!