简体   繁体   English

Rails控制台将无法连接到数据库

[英]rails console won't connect to database

I have a database.yml that uses environment variables, eg: 我有一个使用环境变量的database.yml,例如:

production:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: <%= ENV['RAILS_DB_NAME'] %>
  pool: 5
  host: 127.0.0.1
  port: 3306
  username: <%= ENV['RAILS_DB_USER'] %>
  password: <%= ENV['RAILS_DB_PASS'] %>

However, when I use: 但是,当我使用:

$ export RAILS_DB_NAME="rails_db"
$ rails c production
> User.all
I get an error:
Mysql2::Error: Access denied for user 'root'@'localhost' (using password: NO)

I can see my environement variable in the same console: 我可以在同一控制台中看到我的环境变量:

> ENV['RAILS_DB_NAME']
"rails_db"

But if I dump the active connection config it is nil: 但是,如果我转储活动的连接配置,它将为零:

> ActiveRecord::Base.connection_config
{:adapter=>"mysql2", :encoding=>"utf8", :reconnect=>false, :database=>nil, :pool=>5, :host=>"127.0.0.1", :port=>3306, :username=>nil, :password=>nil}

Any ideas what is going wrong? 任何想法出了什么问题?

How can I trace why rails app isn't getting the environment variables? 我如何追踪为什么Rails应用程序没有获取环境变量?

TIA! TIA!

Update: I should clarify that $ rails db works perfectly. 更新:我应该澄清一下$ rails db可以正常工作。 It's only $ rails c that can't connect to db. 只有$ rails c无法连接到数据库。

Update 2: When I clone down the project to a new folder and bundle install it works perfectly fine there. 更新2:当我将项目克隆到一个新文件夹并捆绑安装时,它在那儿工作得很好。 It must be something with my folder. 我的文件夹一定有东西。 Diff doesn't show any differences. 差异未显示任何差异。 Weird! 奇怪的!

Its not so much Rails/ActiveRecord but MySQL is not allowing the connection. 它没有太多的Rails / ActiveRecord,但是MySQL不允许连接。 Why is your username and password not specified in config/database.yml ? 为什么在config/database.yml未指定您的usernamepassword

Open a MySQL console and run this: 打开一个MySQL控制台并运行:

> grant all on rails_db.* to root@localhost;

(replace rails_db with whatever is your actual DB name.) (将rails_db替换为您的实际数据库名称。)

This will allow incoming connections based on the default username=root and a blank password. 这将允许基于默认username=root和空密码的传入连接。 If you do end up specifying a username and password in your config, then re-run the grant statement with those credentials. 如果最终在配置中指定了usernamepassword ,请使用这些凭据重新运行Grant语句。

Eg 例如

> grant all on rails_db.* to root@localhost identified by 'somepassword';

I have found out the fix - but I am not sure why this is a problem.. but.. rails doesn't like having a project in a folder named rails! 我已经找到了解决方法-但是我不确定为什么这是一个问题..但是.. rails不喜欢在名为rails的文件夹中有一个项目!

My rails project was in a folder: 我的rails项目在一个文件夹中:

/var/deployed/rails

when I rename it to: 当我将其重命名为:

/var/deployed/myapp 

Then $ rails console works perfectly to talk to the db. 然后$ rails控制台可以完美地与数据库对话。

Weird! 奇怪的!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM