Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disconnect from a particular database in rails?

I use this snippet to connect to another db

ActiveRecord::Base.establish_connection....

but I don't know how to delete this connection after it is not needed.

like image 206
Andrey Yasinishyn Avatar asked Sep 09 '13 11:09

Andrey Yasinishyn


3 Answers

You can call remove_connection

old_connection = ActiveRecord::Base.remove_connection

If you have done something like the following (where there is an assignment)

new_connection = ActiveRecord::Base.establish_connection(...)

This can be passed on to remove_connection

old_connection = ActiveRecord::Base.remove_connection(new_connection)

You can find it in the source code.

like image 64
deefour Avatar answered Nov 29 '22 02:11

deefour


The answer is indeed remove_connection( klass=self). However, establish_connection(...) returns the connection, not the base class, so the code instead should be:

ActiveRecord::Base.establish_connection(...)
ActiveRecord::Base.remove_connection( ActiveRecord::Base)

To differentiate different connections (useful for handling multiple databases, for example), you can create a subclass to make it easier. This will only disconnect the associated connection, and even with repeated calls, none belonging to the parent class.

For example:

class MyDatabase::Base < ActiveRecord::Base
  def example_connection_and_disconnection
    MyDatabase::Base.establish_connection(...)
    MyDatabase::Base.remove_connection( MyDatabase::Base)
  end
end

Hope this helps others out there. :-)

like image 37
Kitebuggy Avatar answered Nov 29 '22 03:11

Kitebuggy


 your_connection = ActiveRecord::Base.establish_connection(...)

 ActiveRecord::Base.remove_connection(your_connection)
like image 42
Rajarshi Das Avatar answered Nov 29 '22 02:11

Rajarshi Das