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.
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.
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. :-)
your_connection = ActiveRecord::Base.establish_connection(...)
ActiveRecord::Base.remove_connection(your_connection)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With