Albert Paul
Albert Paul

Reputation: 1218

Rails - How to access tables from external Database

I need to get some data from external db(Not the primary one). So I added a connection entry in database.yml.

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

Also I've created a class to address it, external_reporting_db.rb

class ExternalReportingDB < ActiveRecord::Base
  self.abstract_class = true
  establish_connection :external_reporting_table
end

I've this model I need to get the data from external db, 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

What should I do to access a table from external db in custom_report.rb ?

Upvotes: 9

Views: 6076

Answers (1)

Jimmy Baker
Jimmy Baker

Reputation: 3255

When I do this, I do it according to what ActiveRecord expects which is a single model class per table. For example, let's say my external db has a table called customers, then I would define a class called "ExternalCustomers" and set the establish_connection and the table name inside the class. Here's an example:

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

Then you can use it as you would any other AR model:

ExternalCustomer.where(id: 123)

If you don't want to add new models for every table, you can query the external db through the connection. Example:

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

Upvotes: 13

Related Questions