connection
- 1.0.0 (0)
- 1.1.6 (0)
- 1.2.6 (0)
- 2.0.3 (0)
- 2.1.0 (0)
- 2.2.1 (0)
- 2.3.8 (0)
- 3.0.0 (0)
- 3.0.9 (-1)
- 3.1.0 (0)
- 3.2.1 (0)
- 3.2.8 (0)
- 3.2.13 (0)
- 4.0.2
- 4.1.8
- 4.2.1
- 4.2.7
- 4.2.9
- 5.0.0.1
- 5.1.7
- 5.2.3
- 6.0.0
- 6.1.3.1
- 6.1.7.7
- 7.0.0
- 7.1.3.2
- 7.1.3.4
- What's this?
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.
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
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")
Current Database Name: Sqlite version
Get the current database name when using Sqlite:
ActiveRecord::Base.connection.instance_variable_get(:@config)[:database].split('/').last
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
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)