method

establish_connection

Importance_3
v2.2.1 - Show latest stable - 2 notes - Class: ActiveRecord::Base
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.

Show source
Register or log in to add new notes.
July 3, 2008
5 thanks

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.

January 26, 2013 - (v3.0.0 - v3.2.8)
0 thanks

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”