你可以得到数据库的用户名,PW,数据库名称在Rails的? [英] Can you get DB username, pw, database name in Rails?

查看:250
本文介绍了你可以得到数据库的用户名,PW,数据库名称在Rails的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个rake任务,做的Rails / ActiveRecord的外一些数据库的工作。

有没有一种方法来获取数据库连接信息(主机,用户名,密码,数据库名称)在的database.yml 定义当前的环境?

我想获得它,所以我可以用它来连接这样的...

  CON = Mysql.real_connect(主机,用户,私服,current_db)
 

解决方案

从轨道内,你可以创建一个配置对象,并从中获取必要的信息:

 配置= Rails.configuration.database_configuration
主机=配置[Rails.env] [主机]
数据库=配置[Rails.env] [数据库]
用户名=配置[Rails.env] [用户名]
密码=配置[Rails.env] [密码]
 

见导轨文档 ::配置的详细信息。

这只是使用 YAML ::负荷加载从数据库配置文件(配置的database.yml ),你可以用自己的Rails环境之外获得的信息:

 要求YAML
信息= YAML ::负载(IO.read(database.yml中))
打印信息[生产] [主机]
打印信息[生产] [数据库]
...
 

I'm writing a rake task that does some DB work outside of Rails/ActiveRecord.

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")

解决方案

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"]

See the documentation for Rails::Configuration for details.

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"]
...

这篇关于你可以得到数据库的用户名,PW,数据库名称在Rails的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆