简体   繁体   中英

Active record reset database connection issues - ActiveRecord::Connection.clear_active_connections

Can some body explain me what does these two function exactly do, i am not able to understand it through rails api.

  ActiveRecord::Connection.clear_active_connections!
  ActiveRecord::Connection.clear_all_connections!()

I am working on an application, in which i have to make dynamic db connection. Do i need to put these lines before making a new connection. When i make a new connection what happens to old connection, since i do not remove it explicitly, does this happens automatically ?

First off, I think you want ActiveRecord::Base.connection

I'm looking at these issues now. As best I can tell ActiveRecord::Base.establish_connection will drop all prior connections from the pool and only use the new connection.

I'm running into issues when I'm swapping back and forth and changing connections both at the ActiveRecord::Base level and at the individual model level (ie User.establish_connection . Under certain circumstances, I find that if I establish a connection on the model, then establish a connection on ActiveRecord::Base (intending to also use the new connection on the model), the model will retain the connection.

To wit:

$ ActiveRecord::Base.connection_config[:host]
-> main
$ User.connection_config[:host]
-> main

$ User.establish_connection :blah
$ User.connection_config[:host]
-> blah
$ ActiveRecord::Base.connection_config[:host]
-> main

$ ActiveRecord::Base.establish_connection :blah
$ User.connection_config[:host]
-> blah
$ ActiveRecord::Base.connection_config[:host]
-> blah

$ ActiveRecord::Base.establish_connection :main
$ User.connection_config[:host]
-> blah
$ ActiveRecord::Base.connection_config[:host]
-> main

The important point to note here is that, since you've established the connection on the User model explicitly, ActiveRecord knows to use a different connection pool than that used for the other children of ActiveRecord::Base ; thus, when you switch the ActiveRecord::Base connection back, it doesn't switch all models, just the ones sharing the main connection pool.

Here's the ConnectionHandler doc: http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/ConnectionHandler.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM