How to disconnect from a specific database in rails?

I use this snippet to connect to another db

ActiveRecord::Base.establish_connection.... 

but I do not know how to remove this connection after it is not needed.

+6
source share
3 answers

You can call remove_connection

 old_connection = ActiveRecord::Base.remove_connection 

If you have done something like the following (where there is a task)

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

This can be passed to remove_connection

 old_connection = ActiveRecord::Base.remove_connection(new_connection) 

You can find it in the source code .

+8
source
  your_connection = ActiveRecord::Base.establish_connection(...) ActiveRecord::Base.remove_connection(your_connection) 
+2
source

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

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

To distinguish between different connections (for example, useful for processing multiple databases), you can create a subclass to simplify it. This will disconnect the connected connection, and even with repeated calls that do not belong to the parent class.

For instance:

 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. :-)

0
source

Source: https://habr.com/ru/post/953475/


All Articles