method

connection

Importance_4
v3.0.0 - Show latest stable - 5 notes - 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.

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

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

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:

ActiveRecord::Base.connection.instance_variable_get(:@config)[:database].split('/').last
November 3, 2010 - (<= 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.

ActiveRecord::Base.connection.schema_search_path.split(",").first
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
    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)