1

In my case. I have use two different databases in my single application. One is mysql and another one is sqlsever.

ActiveRecord::Base.connection.tables

Using this command i have see all table in my mysql database tables. But i don't know the command to see specific database table using rails console.

Santosh Kumbhar
  • 183
  • 3
  • 15

2 Answers2

0

Try below code:

a=ActiveRecord::Base.establish_connection(
  :adapter=> "adapter_name",
  :encoding=> "utf8",
  :reconnect=> "false",
  :database=> "db_name",
  :pool=> "5",
  :username=> "xxxx",
  :password=> "xxxxxxx",
  :host=>"xx.xx.xx.xx"
)

a.connection.tables
puneet18
  • 4,341
  • 2
  • 21
  • 27
  • thank for reply but i got error..ActiveRecord::Base.establish_connection("#{development_sec}").connection.tables NameError: undefined local variable or method `development_sec' for main:Object – Santosh Kumbhar Nov 28 '17 at 06:15
  • have you added database configuration in database.yml file ? – puneet18 Nov 28 '17 at 06:16
  • this is my database.yml file development_sec: mode: dblib adapter: sqlserver dataserver: 123.201.**.*** database: ZKA username: sa password: pass – Santosh Kumbhar Nov 28 '17 at 06:17
  • i have done all this things already.. but still same error is occurring. "NameError: undefined local variable or method `development_sec' for main:Object" – Santosh Kumbhar Nov 28 '17 at 06:26
  • @SantoshKumbhar accept my answer on https://stackoverflow.com/questions/47448715/how-to-access-multiple-databases-in-single-rails-application-in-rails-4/47448896#47448896 – puneet18 Nov 28 '17 at 07:31
  • @SantoshKumbhar vote my answer also if it works for you. Thanks – puneet18 Nov 28 '17 at 07:31
  • How do we find the host? – Karan Sapolia Jul 06 '21 at 06:05
0

The bellow code returns array of all tables present in particular database connection mentioned in the database.yml.

ActiveRecord::Base.establish_connection(Rails.configuration.database_configuration["#{other_connection_name}"]).connection.tables

Where other_connection_name is the name of connection to DB mentioned in database.yml.

For example database.yml

development:
  adapter: mysql2
  encoding: utf8
  collation: utf8_bin
  reconnect: true
  database: dev_schema
  pool: 5
  username: xxx
  password: xxxx
  host: localhost

otherconnection:
  adapter: mysql2
  encoding: utf8
  collation: utf8_bin
  reconnect: true
  database: gbl_schema
  pool: 5
  username: xxx
  password: xxx
  host: localhost

For above database.yml we use bellow code to retrieve all tables present in dev_schema and gbl_schema respectively

ActiveRecord::Base.establish_connection(Rails.configuration.database_configuration["development"]).connection.tables
ActiveRecord::Base.establish_connection(Rails.configuration.database_configuration["otherconnection"]).connection.tables
Satishakumar Awati
  • 3,604
  • 1
  • 29
  • 50