你可以在Rails中获取数据库用户名,pw,数据库名称吗? [英] 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.
是否有办法获取数据库连接信息, c>
Is there a way to get the DB connection info (host, username, password, DB name) for the current environment as defined in database.yml
?
我想要在 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"]
http://api.rubyonrails.org/classes/Rails/Configuration.html =noreferrer>文档 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中获取数据库用户名,pw,数据库名称吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!