ruby-on-rails - 仅在一个 block 中建立与另一个数据库的连接?

标签 ruby-on-rails ruby

在一个 Rails 应用程序中,我在纯 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 的连接发生了变化,其他请求稍后在新连接上执行。

是否可以只在一个 block 中建立连接并返回到旧连接。我知道我可以建立另一个连接,但这对性能非常不利。

最佳答案

如果您将所有数据库连接都保存在 database.yml 中就好了

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

other_envs:
.....

然后创建一个类

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

从你的 Controller 你可以像访问一样

OtherDB.table_name = "table_name"
OtherDB.first

在这里查看我的博客 http://imnithin.github.io/multiple-database.html

关于ruby-on-rails - 仅在一个 block 中建立与另一个数据库的连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26574086/

相关文章:

ruby - 谁能弄清楚这段 ruby​​ 代码的作用?

ruby-on-rails - 如何使用apache bench在url中指定查询字符串

ruby-on-rails - 我应该使用哪些插件/gem 在 Rails 3 中即时动态生成缩略图?

ruby-on-rails - 在 Rails ActiveRecord 测试套件中使用 Ruby 1.9 lambda 文字感到困惑

javascript - 从 Javascript 调用 Rails Helper

ruby - 使用 RSpec(LeakyConstantDeclaration 问题)生成不泄漏的动态测试的最佳方法?

javascript - 如何在同时使用 Javascript 和 ERB 模板时保持 DRY (Rails)

ruby-on-rails - 在 RHEL 6(x86_64 arch) 中使用 rvm 构建 32 位 ruby

ruby-on-rails - 我应该把这段代码放在哪里?

ruby-on-rails - 如何在 ruby​​ 中创建 SSH 公钥/私钥对并将它们存储在 Db 中