我有一个使用环境变量的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'] %>
然而,当我使用:
$ 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)
我可以在同一个控制台中看到我的environement变量:
> ENV['RAILS_DB_NAME']
"rails_db"
但如果我转储活动连接配置,则为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}
任何想法出了什么问题?
如何跟踪rails app无法获取环境变量的原因?
TIA!
更新:我应该澄清$ rails db完美运行。只有$ rails c才能连接到db。
更新2:当我将项目克隆到新文件夹并进行捆绑安装时,它在那里工作得很好。 必须是我的文件夹。 Diff没有显示任何差异。怪异!
答案 0 :(得分:1)
它不是Rails / ActiveRecord,而是MySQL不允许连接。为什么username
中没有指定password
和config/database.yml
?
打开MySQL控制台并运行:
> grant all on rails_db.* to root@localhost;
(将rails_db
替换为您的实际数据库名称。)
这将允许基于默认username=root
的传入连接和空密码。如果您最终在配置中指定了username
和password
,请使用这些凭据重新运行grant语句。
E.g。
> grant all on rails_db.* to root@localhost identified by 'somepassword';
答案 1 :(得分:0)
我找到了修复程序 - 但我不确定为什么这是一个问题..但是... rails不喜欢在名为rails的文件夹中有一个项目!
我的rails项目位于文件夹中:
/var/deployed/rails
当我将其重命名为:
/var/deployed/myapp
然后$ rails console可以很好地与数据库通信。
怪异!