Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No database connection in rails console

My rails application works fine when I run rake db:migrate but the problem occurs when I try to start the rails console.

2.0.0p247 :003 > User
 => User(no database connection)
like image 768
ben Avatar asked Jan 11 '14 12:01

ben


4 Answers

That is due to ActiveRecord establishing the connection lazily starting 4.0. Just don't worry about it.

After it's established the first time, you'll start seeing the expected output. Try this:

2.1.4 :001 > User
# => User (call 'User.connection' to establish a connection)

2.1.4 :001 > User.count
# => SELECT COUNT(*) FROM "users" ...

2.1.4 :001 > User
# => User(id: integer, email: string, encrypted_password: string, ...)
like image 144
gmile Avatar answered Sep 22 '22 04:09

gmile


simple solution: The console probably does have a database connection but is reporting that it doesn't.

To see if that's true, make a query in the console.

User.count 

That fixed the false positive warning for me and a colleague.

or

Use Model.connection to establish a connection.

like image 26
ben Avatar answered Sep 25 '22 04:09

ben


To restore the behavior of ActiveRecord models displaying their column information immediately after the console has loaded, here is one workaround:

# config/application.rb
console do
  ActiveRecord::Base.connection
end
like image 29
Rubyist Avatar answered Sep 26 '22 04:09

Rubyist


That isn't a problem. All that's happening is the connection is not instantiated until it's needed.

like image 35
Tony Hopkinson Avatar answered Sep 24 '22 04:09

Tony Hopkinson