Rails - 如何从外部数据库访问表

Alb*_*aul 5 ruby mysql ruby-on-rails ruby-on-rails-3

我需要从外部数据库(不是主数据库)获取一些数据.所以我在database.yml中添加了一个连接条目.

external_reporting_table:
  adapter: mysql2
  encoding: utf8
  database: reporting_db
  host: localhost
  username: root
  password: password
Run Code Online (Sandbox Code Playgroud)

我还创建了一个类来解决它,external_reporting_db.rb

class ExternalReportingDB < ActiveRecord::Base
  self.abstract_class = true
  establish_connection :external_reporting_table
end
Run Code Online (Sandbox Code Playgroud)

我有这个模型我需要从外部数据库,custom_report.rb获取数据

class CustomReport < ExternalReportingDB
  def self.shop_data_collection_abstract(batch_selections)
    p "Here I need to get multiple data from external db's tables."
  end
end
Run Code Online (Sandbox Code Playgroud)

如何从custom_report.rb中的外部数据库访问表?

Jim*_*ker 9

当我这样做时,我根据ActiveRecord期望的每个表的单个模型类来做.例如,假设我的外部数据库有一个名为customers的表,然后我将定义一个名为"ExternalCustomers"的类,并在类中设置establish_connection和表名.这是一个例子:

class ExternalCustomer < ActiveRecord::Base
  establish_connection :external_reporting_table
  table_name "customers"
end
Run Code Online (Sandbox Code Playgroud)

然后您可以像使用任何其他AR模型一样使用它:

ExternalCustomer.where(id: 123)
Run Code Online (Sandbox Code Playgroud)

如果您不想为每个表添加新模型,则可以通过连接查询外部数据库.例:

ExternalReportingDB.connection.execute("select * from whatever...")
Run Code Online (Sandbox Code Playgroud)