【问题标题】:Rails - How to access tables from external DatabaseRails - 如何从外部数据库访问表
【发布时间】:2016-02-18 21:03:19
【问题描述】:

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

external_reporting_table:
  adapter: mysql2
  encoding: utf8
  database: reporting_db
  host: localhost
  username: root
  password: password

我还创建了一个类来解决它,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 中的外部数据库访问表?

【问题讨论】:

    标签: mysql ruby-on-rails ruby ruby-on-rails-3


    【解决方案1】:

    当我这样做时,我会根据 ActiveRecord 的期望来做,即每个表都有一个模型类。例如,假设我的外部数据库有一个名为customers 的表,那么我将定义一个名为“ExternalCustomers”的类,并在类中设置建立连接和表名。这是一个例子:

    class ExternalCustomer < ActiveRecord::Base
      establish_connection :external_reporting_table
      table_name "customers"
    end
    

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

    ExternalCustomer.where(id: 123)
    

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

    ExternalReportingDB.connection.execute("select * from whatever...")
    

    【讨论】:

    • 谢谢,我知道这种方法,我正在寻找任何其他方法来处理外部数据库表,而无需创建额外的模型。
    • @AlbertPaul 这是 Rails 的方式。为什么不想使用 ActiveRecord?
    猜你喜欢
    • 1970-01-01
    • 2020-11-30
    • 2014-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多