【发布时间】:2017-11-28 06:10:06
【问题描述】:
就我而言。 我在我的单个应用程序中使用了两个不同的数据库。 一个是mysql,一个是sqlsever。
ActiveRecord::Base.connection.tables
使用这个命令,我可以看到我的 mysql 数据库表中的所有表。 但我不知道使用 rails 控制台查看特定数据库表的命令。
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4
就我而言。 我在我的单个应用程序中使用了两个不同的数据库。 一个是mysql,一个是sqlsever。
ActiveRecord::Base.connection.tables
使用这个命令,我可以看到我的 mysql 数据库表中的所有表。 但我不知道使用 rails 控制台查看特定数据库表的命令。
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4
试试下面的代码:
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
【讨论】:
下面的代码返回database.yml中提到的特定数据库连接中存在的所有表的数组。
ActiveRecord::Base.establish_connection(Rails.configuration.database_configuration["#{other_connection_name}"]).connection.tables
其中 other_connection_name 是 database.yml 中提到的与 DB 的连接名称。
例如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
对于上面的 database.yml,我们使用下面的代码分别检索 dev_schema 和 gbl_schema 中存在的所有表
ActiveRecord::Base.establish_connection(Rails.configuration.database_configuration["development"]).connection.tables
ActiveRecord::Base.establish_connection(Rails.configuration.database_configuration["otherconnection"]).connection.tables
【讨论】: