Ruby on Rails latest stable (v5.2.3) - 5 notes - Class: ActiveRecord::Base

Method deprecated or moved

This method is deprecated or moved on the latest stable version. The last existing version (v3.2.13) is shown here.

These similar methods exist in v5.2.3:

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.

Show source
Register or log in to add new notes.
August 20, 2008
4 thanks

Current Database Name

The MySQL database adapter extends this and allows you to call


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.


November 7, 2008 - (v1.0.0 - v2.1.0)
0 thanks

Using your model's connection

It’s possible to execute raw SQL over the currently established connection for a model.

You may configure Rails to use different databases for different models. To make sure you are querying the correct database you may do the following:

MyModel.connection.execute("UPDATE `my_models` SET `beer`='free' WHERE 1")
August 12, 2009
0 thanks

Current Database Name: Sqlite version

Get the current database name when using Sqlite:

November 3, 2010 - (v2.3.2 - v2.3.8)
0 thanks

Get the primary schema's name

If you’re using PostgreSQL and you’ve changed schema, sometimes you need to know what schema you’re in.

March 15, 2011
0 thanks

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
      10.times do
        connection.execute("SELECT SLEEP(1)")  # WRONG
        ActiveRecord::Base.connection.execute("SELECT SLEEP(1)")  # CORRECT
      puts "success"
    rescue => e
      puts e.message