Method: ActiveRecord::Base.establish_connection

Defined in:
activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb

.establish_connection(spec = nil) ⇒ Object

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.



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb', line 51

def self.establish_connection(spec = nil)
  case spec
    when nil
      raise AdapterNotSpecified unless defined?(Rails.env)
      establish_connection(Rails.env)
    when ConnectionSpecification
      self.connection_handler.establish_connection(name, spec)
    when Symbol, String
      if configuration = configurations[spec.to_s]
        establish_connection(configuration)
      else
        raise AdapterNotSpecified, "#{spec} database is not configured"
      end
    else
      spec = spec.symbolize_keys
      unless spec.key?(:adapter) then raise AdapterNotSpecified, "database configuration does not specify adapter" end

      begin
        require "active_record/connection_adapters/#{spec[:adapter]}_adapter"
      rescue LoadError => e
        raise "Please install the #{spec[:adapter]} adapter: `gem install activerecord-#{spec[:adapter]}-adapter` (#{e})"
      end

      adapter_method = "#{spec[:adapter]}_connection"
      unless respond_to?(adapter_method)
        raise AdapterNotFound, "database configuration specifies nonexistent #{spec[:adapter]} adapter"
      end

      remove_connection
      establish_connection(ConnectionSpecification.new(spec, adapter_method))
  end
end