Reputation: 1861
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.
Upvotes: 10
Views: 7484
Reputation: 99
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. :-)
Upvotes: 1
Reputation: 12320
your_connection = ActiveRecord::Base.establish_connection(...)
ActiveRecord::Base.remove_connection(your_connection)
Upvotes: 3
Reputation: 35350
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.
Upvotes: 11