Today I Learned

hashrocket A Hashrocket project

Ensure you're always using the same connection

In Rails, if you want to ensure that you are using the same database connection from the connection pool to execute a number of commands, you can use the ActiveRecord::Base.with_connection method.

This method yields a single connection from the pool for you to execute your commands against:

ActiveRecord::Base.with_connection do |conn|
  conn.execute("select * from sessions")
end

It is important to note that the connection yielded is taken out of the pool until the processing in the block is complete.

See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.