Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 207
Albert Paul Avatar asked Feb 18 '16 21:02

Albert Paul


People also ask

Can rails connect to multiple databases?

Rails now has support for multiple databases so you don't have to store your data all in one place. At this time the following features are supported: Multiple writer databases and a replica for each. Automatic connection switching for the model you're working with.

How do I view a database in rails?

You can use rails dbconsole to view the database that your rails application is using. It's alternative answer rails db . Both commands will direct you the command line interface and will allow you to use that database query syntax.

What database does rails use by default?

Rails defaults to using a SQLite database when creating a new project, but you can always change it later.


1 Answers

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...")
like image 69
Jimmy Baker Avatar answered Sep 22 '22 01:09

Jimmy Baker