establish_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 (-2)
- 3.1.0 (0)
- 3.2.1 (5)
- 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?
establish_connection(spec = nil)
public
Establishes the connection to the database. Accepts a hash as input where the :adapter key must be specified with the name of a database adapter (in lower-case) example for regular databases (MySQL, Postgresql, etc):
ActiveRecord::Base.establish_connection( :adapter => "mysql", :host => "localhost", :username => "myuser", :password => "mypass", :database => "somedatabase" )
Example for SQLite database:
ActiveRecord::Base.establish_connection( :adapter => "sqlite", :database => "path/to/dbfile" )
Also accepts keys as strings (for parsing from yaml for example):
ActiveRecord::Base.establish_connection( "adapter" => "sqlite", "database" => "path/to/dbfile" )
The exceptions AdapterNotSpecified, AdapterNotFound and ArgumentError may be returned on an error.

Connections to multiple databases
establish_connection can be used to connect to multiple databases. The immediate downside is that your rake migrations may not work properly without hacking.
In each model that resides in a different database we call:
establish_connection :different_database
You can check they are working by hitting script/console with:
>> App.connection.instance_eval {@config[:database]} => "app_development" >> AnotherDatabase.connection.instance_eval {@config[:database]} => "another_database"
Now doing a call to AnotherDatabase.find() will connect to the AnotherDatabase database and start returning results.

Use sqlite3, not sqlite
Note that typically if you want to connect to an SQLite database the adapter would be “sqlite3”; not “sqlite” as depicted in the documentation above. Just using the term “sqlite” might result in the error message: “database configuration specifies nonexistent sqlite adapter”