Ruby-on-rails 您可以在 Rails 中获取数据库用户名、密码、数据库名称吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/399396/
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-02 20:51:55  来源:igfitidea点击:

Can you get DB username, pw, database name in Rails?

ruby-on-railsrubydatabaseactiverecordenvironment

提问by Ethan

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

我正在编写一个 rake 任务,它在 Rails/ActiveRecord 之外执行一些 DB 工作。

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

回答by Robert Gamble

From within rails you can create a configuration object and obtain the necessary information from it:

在 rails 中,您可以创建一个配置对象并从中获取必要的信息:

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 documentationfor Rails::Configuration for details.

有关详细信息,请参阅Rails::Configuration的文档

This just uses YAML::loadto load the configuration from the database configuration file (database.yml) which you can use yourself to get the information from outside the rails environment:

这只是使用YAML::load从数据库配置文件 ( database.yml)加载配置,您可以使用它从 rails 环境外部获取信息:

require 'YAML'
info = YAML::load(IO.read("database.yml"))
print info["production"]["host"]
print info["production"]["database"]
...

回答by KenB

Bryan's answer in the comment above deserves a little more exposure:

布莱恩在上述评论中的回答值得更多曝光:

>> Rails.configuration.database_configuration[Rails.env]
=> {"encoding"=>"unicode", "username"=>"postgres", "adapter"=>"postgresql", "port"=>5432, "host"=>"localhost", "password"=>"postgres", "database"=>"mydb", "pool"=>5}

回答by qqbenq

ActiveRecord::Base.connection_config

returns the connection configuration in a hash:

以散列形式返回连接配置:

=> {:adapter=>ADAPTER_NAME, :host=>HOST, :port=>PORT, 
    :database=>DB, :pool=>POOL, :username=>USERNAME, 
    :password=>PASSWORD} 


As tpettremarked in their comment: this solution accounts for merging the configuration from database.ymland from the environment variable DATABASE_URL.

正如tpett他们在评论中所说:这个解决方案考虑了database.yml从环境变量合并配置DATABASE_URL

回答by derosm2

I think this is the simplest solution. After some testing (in Rails 5.2 at least) this will resolve DATABASE_URL correctly.

我认为这是最简单的解决方案。经过一些测试(至少在 Rails 5.2 中)这将正确解析 DATABASE_URL。

 ActiveRecord::Base.configurations[Rails.env]

回答by edwardsharp

Old question but this was one of my first stops in looking up how to do this so I figure this may help someone else. I normally have .my.cnf files in the home directory. So using the 'parseconfig' gem and some ERB syntax in my database.yml config file means I've got dynamic file that I can feel good about checking into source control and also simplify deployments (in my case). Also note the list of common sockets, this makes it easier to move my app to different operating systems that might have a different Unix socket path.

老问题,但这是我查找如何执行此操作的第一站之一,因此我认为这可能对其他人有所帮助。我通常在主目录中有 .my.cnf 文件。因此,在我的 database.yml 配置文件中使用 'parseconfig' gem 和一些 ERB 语法意味着我有一个动态文件,我可以在检查源代码控制和简化部署时感觉良好(在我的情况下)。还要注意常见套接字列表,这可以更轻松地将我的应用程序移动到可能具有不同 Unix 套接字路径的不同操作系统。

<% 
    require 'parseconfig'
    c=ParseConfig.new('../../.my.cnf') %>

mysqlevn: &mysql
  adapter: mysql 
  username: <%= c.params['client']['user'] %>
  password: <%= c.params['client']['password'] %>
  host: localhost 
  socket: <%= [ 
  '/var/run/mysqld/mysqld.sock',
  '/var/lib/mysql/mysql.sock',
  '/tmp/mysqld.sock',
  '/tmp/mysql.sock'].detect { |socket| File.exist?(socket) } %>

production:
  database: app_production
  <<: *mysql


development:
  database: app_development 
  <<: *mysql

# Do not set this db to the same as development or production.
test:
  database: app_test
  <<: *mysql

ref: http://effectif.com/articles/database-yml-should-be-checked-in

参考:http: //effectif.com/articles/database-yml-should-be-checked-in