method
connection
v3.1.0 -
Show latest stable
- Class:
ActiveRecord::Base
connection()public
Returns the connection currently associated with the class. This can also be used to “borrow” the connection to do database work that isn’t easily done without going straight to SQL.
3Notes
Current Database Name
The MySQL database adapter extends this and allows you to call
ActiveRecord::Base.connection.current_database
to get the current databases name. Useful when you are actively changing the database you are connected to and sometimes need to check the current one.
http://apidock.com/rails/ActiveRecord/ConnectionAdapters/MysqlAdapter/current_database
Current Database Name: Sqlite version
Get the current database name when using Sqlite:
ActiveRecord::Base.connection.instance_variable_get(:@config)[:database].split('/').last
Don't cache it!
Don't store a connection in a variable, because another thread might try to use it when it's already checked back in into the connection pool. See: ActiveRecord::ConnectionAdapters::ConnectionPool
connection = ActiveRecord::Base.connection
threads = (1..100).map do
Thread.new do
begin
10.times do
connection.execute("SELECT SLEEP(1)") # WRONG
ActiveRecord::Base.connection.execute("SELECT SLEEP(1)") # CORRECT
end
puts "success"
rescue => e
puts e.message
end
end
end
threads.each(&:join)