9

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 ?

1 Answer 1

13

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...")
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I know this method, I'm looking for any other way to handle external DB tables without creating additional models.
@AlbertPaul This is the Rails way. Why wouldn't you want to use ActiveRecord?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.