peterept
peterept

Reputation: 4427

rails console won't connect to database

I have a database.yml that uses environment variables, eg:

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?

TIA!

Update: I should clarify that $ rails db works perfectly. It's only $ rails c that can't connect to db.

Update 2: When I clone down the project to a new folder and bundle install it works perfectly fine there. It must be something with my folder. Diff doesn't show any differences. Weird!

Upvotes: 1

Views: 2454

Answers (2)

peterept
peterept

Reputation: 4427

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!

My rails project was in a folder:

/var/deployed/rails

when I rename it to:

/var/deployed/myapp 

Then $ rails console works perfectly to talk to the db.

Weird!

Upvotes: 1

Cody Caughlan
Cody Caughlan

Reputation: 32758

Its not so much Rails/ActiveRecord but MySQL is not allowing the connection. Why is your username and password not specified in config/database.yml?

Open a MySQL console and run this:

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

(replace rails_db with whatever is your actual DB name.)

This will allow incoming connections based on the default username=root and a blank password. If you do end up specifying a username and password in your config, then re-run the grant statement with those credentials.

E.g.

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

Upvotes: 1

Related Questions