【问题标题】:can't see tables in specific database using rails console无法使用 rails 控制台查看特定数据库中的表
【发布时间】: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


    【解决方案1】:

    试试下面的代码:

    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
    

    【讨论】:

    • 感谢回复,但我收到错误消息。ActiveRecord::Base.establish_connection("#{development_sec}").connection.tables NameError: undefined local variable or method `development_sec' for main:Object
    • 你在database.yml文件中添加数据库配置了吗?
    • 这是我的 database.yml 文件 development_sec:模式:dblib 适配器:sqlserver 数据服务器:123.201.**.*** 数据库:ZKA 用户名:sa 密码:pass
    • 我已经完成了所有这些事情......但仍然发生同样的错误。 "NameError: main:Object 的未定义局部变量或方法 `development_sec'"
    • @SantoshKumbhar 接受我在 stackoverflow.com/questions/47448715/… 上的回答
    【解决方案2】:

    下面的代码返回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_schemagbl​​_schema 中存在的所有表

    ActiveRecord::Base.establish_connection(Rails.configuration.database_configuration["development"]).connection.tables
    ActiveRecord::Base.establish_connection(Rails.configuration.database_configuration["otherconnection"]).connection.tables
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-12
      • 2021-10-13
      • 2011-04-18
      • 2011-01-07
      • 2019-10-05
      相关资源
      最近更新 更多