Ruby-on-rails 如何检查 ActiveRecord 使用的数据库名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10001583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 03:09:26  来源:igfitidea点击:

how to check the database name that ActiveRecord uses

ruby-on-railsrubyconfiguration

提问by m33lky

In database.yml you define all the settings. How can I access those settings from ruby? I've looked in App::Application::config, but can't find it there. Also, I remember people were able to configure database settings without yaml, does anyone know how?

在 database.yml 中定义所有设置。如何从 ruby​​ 访问这些设置?我已经看过了App::Application::config,但在那里找不到。另外,我记得人们可以在没有 yaml 的情况下配置数据库设置,有谁知道如何?

回答by tsherif

Rails.configuration.database_configuration

This will give you a hash table with the configurations for each of your environments. E.g. to get your development database name:

这将为您提供一个哈希表,其中包含每个环境的配置。例如,获取您的开发数据库名称:

Rails.configuration.database_configuration["development"]["database"]

回答by iGEL

In Rails 4.2, you can do this:

在 Rails 4.2 中,你可以这样做:

ActiveRecord::Base.connection.current_database

You can also ask specific models for their database (since it's possible to use different databases per model):

您还可以询问特定模型的数据库(因为每个模型可以使用不同的数据库):

User.connection.current_database

回答by fairchild

An additional way to get more iformation is to use the database specific connection info methods. For example, if you are using postgresql, you can get details for the current database connection with:

获取更多信息的另一种方法是使用特定于数据库的连接信息方法。例如,如果您使用的是 postgresql,则可以通过以下方式获取当前数据库连接的详细信息:

ActiveRecord::Base.connection.raw_connection.conninfo_hash

This will give more connection details, not only those that differ from defaults.

这将提供更多连接详细信息,而不仅仅是那些与默认值不同的连接详细信息。

回答by tommyb67

To piggyback on the comments from tsherif, you can run the Rails.configuration commands inside the rails console (rails c) to get the database names.

要利用 tsherif 的评论,您可以在 rails 控制台 (rails c) 中运行 Rails.configuration 命令以获取数据库名称。