How to disconnect from a particular database in rails?

和自甴很熟 提交于 2020-04-10 08:10:49

问题


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.


回答1:


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.




回答2:


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

 ActiveRecord::Base.remove_connection(your_connection)



回答3:


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



来源:https://stackoverflow.com/questions/18697008/how-to-disconnect-from-a-particular-database-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!