你能在 Rails 中获取数据库用户名、密码、数据库名称吗? [英] Can you get DB username, pw, database name in Rails?
问题描述
我正在编写一个 rake 任务,它在 Rails/ActiveRecord 之外执行一些数据库工作.
I'm writing a rake task that does some DB work outside of Rails/ActiveRecord.
有没有办法获取database.yml
中定义的当前环境的数据库连接信息(主机、用户名、密码、数据库名称)?
Is there a way to get the DB connection info (host, username, password, DB name) for the current environment as defined in database.yml
?
我想得到它,这样我就可以用它来像这样连接...
I'd like to get it so I can use it to connect like this...
con = Mysql.real_connect("host", "user", "pw", "current_db")
推荐答案
在 rails 中,您可以创建一个配置对象并从中获取必要的信息:
From within rails you can create a configuration object and obtain the necessary information from it:
config = Rails.configuration.database_configuration
host = config[Rails.env]["host"]
database = config[Rails.env]["database"]
username = config[Rails.env]["username"]
password = config[Rails.env]["password"]
有关 Rails::Configuration 的详细信息,请参阅 文档.
See the documentation for Rails::Configuration for details.
这只是使用 YAML::load 从数据库配置文件 (database.yml
),您可以使用它从 rails 环境外部获取信息:
This just uses YAML::load to load the configuration from the database configuration file (database.yml
) which you can use yourself to get the information from outside the rails environment:
require 'YAML'
info = YAML::load(IO.read("database.yml"))
print info["production"]["host"]
print info["production"]["database"]
...
这篇关于你能在 Rails 中获取数据库用户名、密码、数据库名称吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!