Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to do something with ActiveRecord::Base.connection_pool.with_connection

So I know how that this works like this

ActiveRecord::Base.connection_pool.with_connection do |conn|
   conn.execute(sql)
end

but I'm trying to use the connection with actual Activerecord models, so something like

conn.Url.first

is there a way to do something like that?

like image 400
concept47 Avatar asked May 09 '12 19:05

concept47


1 Answers

Found out this isn't possible, but within the with_connection block any ActiveRecord calls should use the connection that is checked out from the Rails connection pool

so in this example

ActiveRecord::Base.connection_pool.with_connection do |conn|
    Url.first
end

It should check out a connection from the pool set aside for Rails in your database.yml :pool setting, let your active record call use it and then check it back in

However, this only works in rails 3+ ... you can see the code change that makes this possible here

Rails 2.3 (old way) http://apidock.com/rails/v2.3.8/ActiveRecord/ConnectionAdapters/ConnectionPool/with_connection

Rails 3 http://apidock.com/rails/v3.0.0/ActiveRecord/ConnectionAdapters/ConnectionPool/with_connection

This guy explains the patch in this blog post http://coderrr.wordpress.com/2009/05/05/activerecords-with_connection-is-now-useful/

like image 176
concept47 Avatar answered Oct 13 '22 05:10

concept47