Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why ActiveRecord::Base.connected? is false, after calling establish_connection

I develop Sinatra application and use there ActiveRecord for working with database, but I encountered one problem. I wrote a test for a model and it breaks with

SQLite3::CantOpenException: unable to open database file

Connection to database is established in test_helper.rb with the following code:

Dir.chdir('..') do
  ActiveRecord::Base.establish_connection(db_config)
end

and ActiveRecord::Base.connected? get false. If I call User.find(:all) for example after connection establishment test will pass and ActiveRecord::Base.connected? will be true. Why? I don't understand.

like image 755
Dmitry Maksimov Avatar asked Aug 18 '10 18:08

Dmitry Maksimov


2 Answers

ActiveRecord::Base.establish_connection only sets up the connection and ActiveRecord does not actually connect until a connection to the database is requested. The following code may help you force ActiveRecord to establish a connection for the connection-pool:

connected = ActiveRecord::Base.connection_pool.with_connection { |con| con.active? }  rescue false

The rescue false hides a couple of potential exceptions (eg. PG::ConnectionBad). Refer to the documentation of :with_connection for more information.

like image 140
Andreas Rayo Kniep Avatar answered Oct 21 '22 16:10

Andreas Rayo Kniep


ActiveRecord::Base.establish_connection is delegated to ActiveRecord::ConnectionAdapters::ConnectionHandler#stablish_connection and if you take a look at its implementation you'll see that it just creates a connection pull

like image 34
Sergey Potapov Avatar answered Oct 21 '22 18:10

Sergey Potapov