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 ?
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.
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.
Rails defaults to using a SQLite database when creating a new project, but you can always change it later.
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...")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With