Rails - 如何从外部数据库访问表
Rails - How to access tables from external Database
我需要从外部数据库(不是主要数据库)获取一些数据。所以我在 database.yml.
中添加了一个连接条目
external_reporting_table:
adapter: mysql2
encoding: utf8
database: reporting_db
host: localhost
username: root
password: password
我还创建了一个 class 来解决它,external_reporting_db.rb
class ExternalReportingDB < ActiveRecord::Base
self.abstract_class = true
establish_connection :external_reporting_table
end
我有这个模型,我需要从外部数据库获取数据,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
我应该怎么做才能从 custom_report.rb 中的外部数据库访问 table?
当我执行此操作时,我会根据 ActiveRecord 的预期进行操作,即每个 table 的单个模型 class。例如,假设我的外部数据库有一个名为 customers 的 table,那么我将定义一个名为 "ExternalCustomers" 的 class 并设置 establish_connection 和 table 名称class里面。这是一个例子:
class ExternalCustomer < ActiveRecord::Base
establish_connection :external_reporting_table
table_name "customers"
end
然后您就可以像使用任何其他 AR 模型一样使用它了:
ExternalCustomer.where(id: 123)
如果你不想为每个table添加新模型,你可以通过连接查询外部数据库。示例:
ExternalReportingDB.connection.execute("select * from whatever...")
我需要从外部数据库(不是主要数据库)获取一些数据。所以我在 database.yml.
中添加了一个连接条目external_reporting_table:
adapter: mysql2
encoding: utf8
database: reporting_db
host: localhost
username: root
password: password
我还创建了一个 class 来解决它,external_reporting_db.rb
class ExternalReportingDB < ActiveRecord::Base
self.abstract_class = true
establish_connection :external_reporting_table
end
我有这个模型,我需要从外部数据库获取数据,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
我应该怎么做才能从 custom_report.rb 中的外部数据库访问 table?
当我执行此操作时,我会根据 ActiveRecord 的预期进行操作,即每个 table 的单个模型 class。例如,假设我的外部数据库有一个名为 customers 的 table,那么我将定义一个名为 "ExternalCustomers" 的 class 并设置 establish_connection 和 table 名称class里面。这是一个例子:
class ExternalCustomer < ActiveRecord::Base
establish_connection :external_reporting_table
table_name "customers"
end
然后您就可以像使用任何其他 AR 模型一样使用它了:
ExternalCustomer.where(id: 123)
如果你不想为每个table添加新模型,你可以通过连接查询外部数据库。示例:
ExternalReportingDB.connection.execute("select * from whatever...")