无法使用 rails 控制台查看特定数据库中的表
can't see tables in specific database using rails console
以我为例。
我在我的单个应用程序中使用了两个不同的数据库。
一个是 mysql,另一个是 sqlsever。
ActiveRecord::Base.connection.tables
使用此命令,我在我的 mysql 数据库 table 中看到了所有 table。
但我不知道使用 rails 控制台查看特定数据库 table 的命令。
试试下面的代码:
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.
中提到的特定数据库连接中存在的所有表的波纹管代码 returns 数组
ActiveRecord::Base.establish_connection(Rails.configuration.database_configuration["#{other_connection_name}"]).connection.tables
其中 other_connection_name 是 database.yml 中提到的数据库的连接名称。
例如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
以我为例。 我在我的单个应用程序中使用了两个不同的数据库。 一个是 mysql,另一个是 sqlsever。
ActiveRecord::Base.connection.tables
使用此命令,我在我的 mysql 数据库 table 中看到了所有 table。 但我不知道使用 rails 控制台查看特定数据库 table 的命令。
试试下面的代码:
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.
中提到的特定数据库连接中存在的所有表的波纹管代码 returns 数组ActiveRecord::Base.establish_connection(Rails.configuration.database_configuration["#{other_connection_name}"]).connection.tables
其中 other_connection_name 是 database.yml 中提到的数据库的连接名称。
例如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